Unity3D: 获取输入/控件焦点
简单来讲,就是
- 用GUI.SetNextControlName为该行代码的下一句控件设置名字
- GUI.FocusControl来把焦点设置到某控件上,这里将用到上一步设置的名字
用GUI.GetNameOfFocusedControl来获得焦点控件的名字。
示例代码1:
GUI.SetNextControlName("Text1"); text1 = GUILayout.TextField(text1); GUI.SetNextControlName("Text2"); text2 = GUILayout.TextField(text2); if (GUI.GetNameOfFocusedControl() == string.Empty) { // Set focus to control Text1. GUI.FocusControl("Text1"); }
官方示例代码:
using UnityEngine; using System.Collections; public class example : MonoBehaviour { public string username = "username"; public string pwd = "a pwd"; void OnGUI() { GUI.SetNextControlName("MyTextField"); // This control will be named MyTextField. username = GUI.TextField(new Rect(10, 10, 100, 20), username); pwd = GUI.TextField(new Rect(10, 40, 100, 20), pwd); if (GUI.Button(new Rect(10, 70, 80, 20), "Move Focus")) GUI.FocusControl("MyTextField"); } }