15

I have this snippet on Windows (VS2017 Community) on Unity 5.6:

public static void setClipboardStr(string str)
{
    try
    {
        if (Clipboard.ContainsText())
        {
            // ...doesn't matter if true or false - 
            // from here on, I can't copy+paste inside 
            // the game or outside until I close the app. 
            // If I had an error instead of try/catch or 
            // check if it contains text, the error will 
            // remain UNTIL I REBOOT (beyond the app closing).
        }
    }
    catch(Exception ex)
    {
        Debug.LogError(ex);
    }
}

Whenever I use Clipboard in any form, even when checking if it's text or not, it destroys the clipboard until I close the app. Now, is this a Unity bug? VS bug? Is there something I'm not understanding? What should I use, instead?

Programmer
  • 121,791
  • 22
  • 236
  • 328
dylanh724
  • 948
  • 1
  • 12
  • 29

1 Answers1

19

Clipboard.ContainsText is from the System.Windows.Forms namespace. These are not supported in Unity. One would be lucky to get it to compile and extremely luck to get work properly since Unity uses Mono. Also, this is not portable so don't use anything from this namespace in Unity.

What should I use, instead?

Write to clipboard:

GUIUtility.systemCopyBuffer = "Hello";

Read from clipboard:

string clipBoard = GUIUtility.systemCopyBuffer;

This should work. If not, you can implement your own clipboard API from scratch using their C++ API. You do have to do this for each platform.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • You rock man, and that speed .... it was so confusing because Clipboard SORT OF worked and was the top answer at tons of forums (....until I later scrolled down to see it's broken). – dylanh724 Jul 29 '17 at 09:03
  • 5
    You are welcome and don't be discouraged to ask future questions because of the down-vote. Your question seems fine with code and everything else. Some people will always down-vote. Happy coding! – Programmer Jul 29 '17 at 09:09