How can I detect when the name of a gameobject has been changed in the editor and do something when that happens?
Asked Answered
O

3

0

I think this has something to do with the editor classes, but I’m not sure.

I have an object A with a child B. B has a UIText.
What I want is that whenever I change A’s gameobject name then B’s text change to the same.

Si I think I have to detect when the change occurs and then capture that event and change the name of the text.

Thanks in advance.

Ophthalmology answered 23/3 at 9:50 Comment(0)
O
0

Nevermind, I think I found a solution:

I created a script with the ExecuteInEditMode descriptor.

[ExecuteInEditMode]
public class ChangeTextAccordingtToName : MonoBehaviour
{
    private string oldName;
    public UnityEngine.UI.Text textToChange;

    void Update ()
    {
        if( name!=oldName && textToChange!=null )
        {
            textToChange.text = name;
        }
        oldName = name;
    }
}
Ophthalmology answered 23/3 at 9:49 Comment(0)
C
0

Still a good question, still not a good answer — a pragmatic one, though.

Charteris answered 5/6, 2019 at 19:52 Comment(0)
P
0

For the case case where we only expect the asset name to be modified in the editor, I think this is a good answer since Update() is only called on user interaction in the Editor. I would improve on it slightly by wrapping this in compilation directives so that oldName is only serialized in the editor:

[ExecuteInEditMode]
public class ChangeTextAccordingtToName : MonoBehaviour {
#if UNITY_EDITOR
    private string oldName;
#endif
    public UnityEngine.UI.Text textToChange;
	// Update is called once per frame
	void Update ()
    {
#if UNITY_EDITOR
        if (name != oldName)
        {
            if (textToChange != null)
            {
                textToChange.text = name;
            }    
        }
        oldName = name;
#endif
	}
}
Pogrom answered 23/3 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.