Unity将文本复制到剪切板

时间:2022-09-14 20:51:58
转载自:http://blog.csdn.net/u011416077/article/details/51513935

需要在android 和iOS中分别实现
iOS端实现
Clipboard.mm
@interface Clipboard : NSObject

extern "C"
{
/* compare the namelist with system processes */
void _copyTextToClipboard(const char *textList);
}

@end


@implementation Clipboard
//将文本复制到IOS剪贴板
- (void)objc_copyTextToClipboard : (NSString*)text
{
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
pasteboard.string = text;
}
@end
extern "C" {
static Clipboard *iosClipboard;
void _copyTextToClipboard(const char *textList)
{
NSString *text = [NSString stringWithUTF8String: textList] ;
if(iosClipboard == NULL)
{
iosClipboard = [[Clipboard alloc] init];
}
[iosClipboard objc_copyTextToClipboard: text];
}
}


安卓端:
public void CopyTextToClipboard(final String text) {
runOnUiThread(new Runnable() {

@Override
public void run() {
ClipboardManager clipboardManager = (ClipboardManager) mInstance.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("playerId", text);
clipboardManager.setPrimaryClip(clipData);
}
});
}

Unity中调用
    using UnityEngine;  
using System.Collections;
using System.Runtime.InteropServices;

public class CMGE_Clipboard {

#if UNITY_IPHONE
/* Interface to native implementation */
[DllImport ("__Internal")]
private static extern void _copyTextToClipboard(string text);
#endif


public static void CopyToClipboard(string input)
{
#if UNITY_ANDROID
// Get the Main Plugin activity class
AndroidJavaClass actClass = new AndroidJavaClass("com.xxx.xxx.PluginActivity");

// Get a reference to an instance of the PluginActivity
AndroidJavaObject pluginActivity = actClass.CallStatic<AndroidJavaObject>("getInstance");

pluginActivity.Call("CopyTextToClipboard", input);

#elif UNITY_IPHONE
_copyTextToClipboard(input);
#elif UNITY_EDITOR
TextEditor t = new TextEditor();
t.content = new GUIContent(input);
t.OnFocus();
t.Copy();
#endif
}
}