As mentioned in part 1, Unity editor is very easily extensible by scripting.
It basically allows to do almost everything you could by clicking by a script. And programmers do not like clicking, if something can be automated.
In the following article, I'll show you some simple steps to achieve some simple results with Unity editor, beginning with the basics of creating an editor script, and focusing on selecting, inspecting and modifying objects in scene. The information below is, of course, available in the Unity documentation - my goal is to put it in one place, in a simple question-answer format.
In the future I'll provide more similar examples, maybe a bit more complex (so that one would show a few editor features/how-to's)
1) How to create a veery basic editor script, accessible from menu?
Create folder named Editor in Assets folder, create a file named SceneTools.cs and put this code inside:
It's veery basic. It simply adds a menu item called "Do something" to Unity's Tools menu (and creates Tools menu itself, if it hasn't been added before). When clicked, it shows "Showing this log" text in the Console view.
Menu looks like this:
If we want to add some function to Unity's menu, we have to use the MenuItem attribute, and the method has to be static.
2) How to create not-so-basic script (maybe connected to scene somehow?)
Ok, let's extend our script. We can add another method below the first one. Remember to change the name in MenuItem annotation (the menu item name). You can add as many methods (and, therefore, items), as you like to your custom menu. Just remember to change the names (in both annotations and methods' names) This time it will log the selected object's name and print it to console (only if at least one object is selected).
And here is our result:
Without the check in if, the line below would throw NRE if no object was selected.
3) How to select the first root object in scene with particular name?
Another method (we select the first object named "Andrew"):
If there is no such object, nothing happens.
For this one and another, update your "using" directives:
4) Ok, how to remove the first object in the scene with particular name?
Here you go (use cautiously!):
If there is no such object in the scene, nothing happens.
To be continued. I think next time I'll prepare one more complex script, doing some made-up task, using the techniques mentioned above (and adding more).
Meta-blogger note for today: I have to find some way to add line-numbering to the embedded code here, and to make it wrap automatically.
No comments:
Post a Comment