Unity TextField实现复制粘贴功能

发表于2018-08-21
评论0 7.4k浏览
很多人吐槽说unity的编辑器文本输入框GUILayout.TextField不能快捷键复制粘贴,实际上并非如此,主要是大家还没掌握到技巧,下面就和大家分享下使用TextField实现复制粘贴功能。

代码如下:
 public static string HandleCopyPaste(int controlID)
    {
        if (controlID == GUIUtility.keyboardControl)
        {
            if (Event.current.type == UnityEngine.EventType.KeyUp && (Event.current.modifiers == EventModifiers.Control || Event.current.modifiers == EventModifiers.Command))
            {
                if (Event.current.keyCode == KeyCode.C)
                {
                    Event.current.Use();
                    TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
                    editor.Copy();
                }
                else if (Event.current.keyCode == KeyCode.V)
                {
                    Event.current.Use();
                    TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
                    editor.Paste();
#if UNITY_5_3_OR_NEWER || UNITY_5_3
                return editor.text; //以及更高的unity版本中editor.content.text已经被废弃,需使用editor.text代替
#else
                    return editor.content.text;
#endif
                }
                else if (Event.current.keyCode == KeyCode.A)
                {
                    Event.current.Use();
                    TextEditor editor = (TextEditor)GUIUtility.GetStateObject(typeof(TextEditor), GUIUtility.keyboardControl);
                    editor.SelectAll();
                }
            }
        }
        return null;
    }
    /// <summary>
    /// TextField复制粘贴的实现
    /// </summary>
    public static string TextField(string value, params GUILayoutOption[] options)
    {
        int textFieldID = GUIUtility.GetControlID("TextField".GetHashCode(), FocusType.Keyboard) + 1;
        if (textFieldID == 0)
            return value;
        //处理复制粘贴的操作
        value = HandleCopyPaste(textFieldID) ?? value;
        return GUILayout.TextField(value, options);
    }
使用上面的TextField,就可以选中想要复制的文本按Ctrl+C,Ctrl+V 进行复制粘贴了。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引