Get selected component in Unity Inspector window

Viewed 496

I'm trying to make a custom inspector with functionality that applies to all kind of built-in components.

What I'm really trying to do is get as a string the name of the property selected in blue in the inspector when I select it. Is there any way? Example: When highlighting Local Position, is there any way to get "Transform Component - LocalPosition (0,0,0); Unity Editor highlighted element

I tried reading the API to know if there's something that could help me but haven't had any luck. Also tried using CustomEditor(TypeOf(Transform)) but I'm not able to access the values when highlighting.

Any help would be really appreciated!

1 Answers

Would the FocusInEvent work for you?

You would have to add an event for every VisualElement or loop through the root and find all VisualElements and add the event to it. You could then get the name of the VisualElement and use that in the handling of the event.

From the documentation about the 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 = "";
    }
}

I've added a working example as you said that it doesn't seem to be working with the editor. The editor implementation is working in my version of unity (2020.3.30f1) with the following code.

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);
    }
}
Related