Unity - Clipboard

From NoskeWiki
Jump to: navigation, search

About

NOTE: This page is a daughter page of: Unity


Unity3D is a multi-platform 3D game engine. This page talks a little bit about how to get and set the system copy/paste clipboard.


Setting Copy or Paste from Unity

I spent a good hour trying to search Google for answers on "Unity C# copy text to clipboard for Android"... most of them didn't work. The one that appear to work on most platforms was this github code from sanukin39, with the key file copied below:

using UnityEngine;
using System.Runtime.InteropServices;
 
public class UniClipboard
{
  static IBoard _board;
  static IBoard board{
    get{
      if (_board == null) {
        #if UNITY_EDITOR
        _board = new EditorBoard();
        #elif UNITY_ANDROID
        _board = new AndroidBoard();
        #elif UNITY_IOS
        _board = new IOSBoard ();
        #endif
      }
      return _board;
    }
  }
 
  public static void SetText(string str){
    Debug.Log ("SetText");
    board.SetText (str);
  }
 
  public static string GetText(){
    return board.GetText ();
  }
}
 
interface IBoard{
  void SetText(string str);
  string GetText();
}
 
class EditorBoard : IBoard {
  public void SetText(string str){
    GUIUtility.systemCopyBuffer = str;
  }
 
  public string GetText(){
    return GUIUtility.systemCopyBuffer;
  }
}
 
#if UNITY_IOS
class IOSBoard : IBoard {
  [DllImport("__Internal")]
  static extern void SetText_ (string str);
  [DllImport("__Internal")]
  static extern string GetText_();
 
  public void SetText(string str){
    if (Application.platform != RuntimePlatform.OSXEditor) {
      SetText_ (str);
    }
  }
 
  public string GetText(){
    return GetText_();
  }
}
#endif
 
#if UNITY_ANDROID
class AndroidBoard : IBoard {
 
  AndroidJavaClass cb = new AndroidJavaClass("jp.ne.donuts.uniclipboard.Clipboard");
 
  public void SetText(string str){
    Debug.Log ("Set Text At AndroidBoard: " + str);
    cb.CallStatic ("setText", str);
  }
 
  public string GetText(){
    return cb.CallStatic<string> ("getText");
  }
}
#endif

... then from any button or Mono Start() function (eg: public class AnyMonoInScene : MonoBehaviour { void Start() {...} }) you can simply call:

 UniClipboard.SetText("HELLO WORLD TEST");
 Debug.Log(UniClipboard.GetText());

This code worked in the Unity editor, and to get it to work on Android, save an extra copy of your project then carefully copy the "Assets/Plugins/Android/uniClipboard.jar" file to the matching folder. I assume iOS works too, but I haven't tested yet.

To make it easier you might opt instead to pay the $5 for this on the Unity Asset Store:

  • UniPasteBoard - worked nicely (seems to have all good reviews).


Links