Copy to Clipboard with a Button (Unity 5.3 solution)

I’ve seen multiple games which make things very easy for the player by providing Copy to Clipboard buttons next to IP addresses inside a multiplayer lobby for example. It’s an extremely convenient solution because the printed out IP might not be interactable with mouse.

The example code below works perfectly in the Unity editor, but not in the built version. I’m using EditorGUIUtility.systemCopyBuffer to access the clipboard - which is an Editor feature only. At least in Unity 5.2 systemCopyBuffer used to be a public member of GUIUtility. In Unity 5.3 this is no longer the case.

Before you point to me other older posts about the subject, please note that the Reflection approach doesn’t seem to work with Unity 5.3 onward either. I’m looking for the most modern approach to this with the latest Unity version (currently 5.3.2f1).

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEditor;

public class GetIP : MonoBehaviour
{
    public bool isExternalAddress;
    private string ipAddress;
    private Text textIP;

    void Start()
    {
        textIP = GetComponent<Text>();

        if (isExternalAddress)
        {
            ipAddress = Network.player.externalIP;
            textIP.text = "INTERNET: " + ipAddress;
        }
        else
        {
            ipAddress = Network.player.ipAddress;
            textIP.text = "LAN: " + ipAddress;
        }
    }

    public void CopyToClipboard()
    {
        EditorGUIUtility.systemCopyBuffer = ipAddress;
    }
}

using UnityEngine; TextEditor te = new TextEditor(); te.text = "plug your text here"; te.SelectAll(); te.Copy();

I had to find this from another thread:

GUIUtility.systemCopyBuffer = "text"

Much more useful than the select all method because you can put text from multiple boxes or really anything at all.

Clipboard.GetText();

i dont have enough permission to post as a comment, that’s the C# way to do it. sorry for being dumb.

internal static string Clipboard
{//https://flystone.tistory.com/138
get
{
TextEditor _textEditor = new TextEditor();
_textEditor.Paste();
return _textEditor.text;
}
set
{
TextEditor _textEditor = new TextEditor
{text = value};

                _textEditor.OnFocus();
                _textEditor.Copy();
            }
        }

void CopyToClipboard(string s) {
TextEditor te = new TextEditor();
te.text = s;
te.SelectAll();
te.Copy();
}

 //Calling the method
 CopyToClipboard("Hello World");