FocusInEvent个对你有用吗?
您必须 for each VisualElement或通过根循环添加一个事件,并找到所有VisualElement并将事件添加到其中.然后,您可以获得VisualElement的名称,并在处理事件时使用该名称.
从关于focus events的文档中
public void CreateGUI()
{
TextField textField = new TextField();
textField.value = placeHolderText;
rootVisualElement.Add(textField);
textField.RegisterCallback<FocusInEvent>(OnFocusInTextField);
textField.RegisterCallback<FocusOutEvent>(OnFocusOutTextField);
}
private void OnFocusInTextField(FocusInEvent evt)
{
// If the text field just received focus and the user might want to write
// or edit the text inside, the placeholder text should be cleared (if active)
if (placeHolderMode)
{
var textField = evt.target as TextField;
textField.value = "";
}
}
我已经添加了一个工作示例,正如您所说,它似乎不适用于编辑器.编辑器实现在我的unity版本(2020.3.30f1)中使用以下代码.
using UnityEngine;
public class FocusScript : MonoBehaviour
{
}
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
[CustomEditor(typeof(FocusScript))]
public class CustomEditorFocus : Editor
{
public override VisualElement CreateInspectorGUI()
{
VisualElement myInspector = new VisualElement();
TextField textField = new TextField();
textField.name = "test text field";
textField.value = "test";
textField.label = "test label";
myInspector.Add(textField);
textField.RegisterCallback<FocusInEvent>(OnFocusInTextField);
return myInspector;
}
private void OnFocusInTextField(FocusInEvent evt)
{
var textField = evt.target as TextField;
Debug.Log("Testing with field: " + textField.name);
}
}