1. 程式人生 > >Unity複製字串到剪下板

Unity複製字串到剪下板

Unity指令碼

在遊戲中,經常需要複製玩家的ID名字等傳送給好友。該需求分三種情況處理,Android平臺 、iOS平臺和 windows平臺

  • unity指令碼
#if UNITY_IPHONE && !UNITY_EDITOR
    [DllImport ("__Internal")]
    private static extern void _copyTextToClipboard(string text);
#endif

    public static void CopyToClipboard(string content)
    {
        if
(!string.IsNullOrEmpty(content)) { BindCSharpToGameObj(); #if UNITY_ANDROID && !UNITY_EDITOR SDKTool.CallJavaFromObject ("CopyTextToClipboard",new object[]{content}); #elif UNITY_IOS && !UNITY_EDITOR _copyTextToClipboard(content); #else TextEditor t = new
TextEditor(); t.text = content; t.OnFocus(); t.Copy(); #endif }
  • iOS端程式碼
void _copyTextToClipboard(const char *string)
{
    //將char型別轉換為NSString型別
    NSString *str = [UnityUtillity stringFromCString:string];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string
= str; }
  • Android端程式碼
    public void CopyTextToClipboard(final String text) {
        runOnUiThread(new Runnable() {
            @TargetApi(android.os.Build.VERSION_CODES.HONEYCOMB)
            @Override
            public void run() {
                ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("playerId", text);
                clipboardManager.setPrimaryClip(clipData);
            }
        });