- Home /
Fire an event when gameObject has been renamed?
I was wondering if I could have a MonoBehaviour
listen to an event, that would get fired when its gameObject
gets renamed.
First, I have to detect that 'something' is being renamed. And then get the selected gameObject from Selection
- to get to the GO that's being renamed, and maybe then send a msg to its children (or raise an event) - where my MB would be sitting there listening for that signal.
I was just checking out Event.current.commandName
, like so (just like in the doc's example):
void OnGUI()
{
Event e = Event.current;
if (e.commandName != "")
print(e.commandName);
}
But, it seems that the only thing it's catching is "UndoRedoPerformed" - If I make a Copy, Paste, Duplicate, etc. It's not detecting those.
Any ideas how to catch that Rename?
PS: I only care about this in the editor, not at runtime.
Thanks.
Sorry to tell you, but you can't create a event for a setter without changing the Source Code of Unity. You could create your own setter/getter with a custom Editor and then you can do the event thing.
Answer by Jamora · Dec 28, 2013 at 02:45 PM
Unity has a custom callback for changes (renaming, deleting, creating etc.) in the hierarchy window: EditorApplication-hierarchyWindowChanged.
You could have an editor window register for these callbacks and then perform the required actions. You might also consider having a static class [InitializeOnLoad], then register for the callback if such functionality is needed constantly.
Thanks. Good find +1 That's pretty cool but, how to know the type of "change" (rename, delete, etc)? - Couldn't find anything in the docs. For deleting/creating, maybe there would be some window that lives in the editor, that counts the number of objects in the scene, and compares with a prevNumObjs
- it's brutal, but works. How about rena$$anonymous$$g though?
Answer by Amitloaf · Sep 18, 2018 at 07:40 AM
This is possible although a bit awkward. If you make a class inherit from AssetPostprocessor, when you rename an object, OnPostprocessAllAssets will be called twice. The first time will have the new name of the file (or files in case you changed a folder) in movedAssets and the old name in movedFromAssetPaths. This also happens on move, not just on rename but with quite a simple path check you should be able to discern the two. The second time will have the new object in importedAssets (again, this will happen for every imported object so it's less useful for you). Hope that helps!
Your answer
Follow this Question
Related Questions
How do I make events in my unity game? i.e a x2 exp per event? 0 Answers
Detecting moment when GameObiect is created in hierarchy. 1 Answer
Assign mouse events for gameobject/collider at runtime 1 Answer
Rename gameobject (game not running, via inspector script) 2 Answers
Scoring System for Pinball 0 Answers