- Home /
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;
}
}
Answer by IgorAherne · Jan 09, 2017 at 10:15 AM
using UnityEngine; TextEditor te = new TextEditor(); te.text = "plug your text here"; te.SelectAll(); te.Copy();
This worked like a charm. Here's it in a more convenient format.
using UnityEngine;
// This needs to be added to a public static class to be used like an extension
public static void CopyToClipboard(this string s)
{
TextEditor te = new TextEditor();
te.text = s;
te.SelectAll();
te.Copy();
}
/*
Example Use Case 1 ::
string s = "https://answers.unity.com";
s.CopyToClipboard();
Example Use Case 2 ::
Text textField;
string s = textField.text;
s.CopyToClipboard();
*/
Answer by mezzostatic · Jan 09, 2017 at 10:19 AM
Clipboard.GetText();
i dont have enough permission to post as a comment, that's the C# way to do it. sorry for being dumb.
Answer by karsnen · Feb 10, 2020 at 10:13 PM
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();
}
}
Answer by MaxLohMusic · Apr 07 at 05:18 AM
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.
Answer by codemaker2015 · Sep 20, 2021 at 08:49 AM
void CopyToClipboard(string s) {
TextEditor te = new TextEditor();
te.text = s;
te.SelectAll();
te.Copy();
}
//Calling the method
CopyToClipboard("Hello World");