Tuesday, 22 June 2021

Unity editor scripting (part 2) - basic menus, basic object selection

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:

using UnityEditor;
using UnityEngine;

public class SceneTools
{
    
    [MenuItem("Tools/Show some log.")]
    static void ShowLog()
    {
        Debug.Log("Showing this log");
    }

}

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).

[MenuItem("Tools/Show selected object's name.")]
static void ShowObjectsName()
{
    if (Selection.gameObjects.Length > 0)
        Debug.Log(Selection.activeGameObject.name);
}

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"):

[MenuItem("Tools/Select object with name.")]
static void SelectObjectWithName()
{

    GameObject[] rootGOs = 
    SceneManager.GetActiveScene().GetRootGameObjects();
    
    foreach (GameObject go in rootGOs)
    {
        if (go.name == "Andrew")
        {
            Selection.activeObject = go;
            break;
        }
    }
}

If there is no such object, nothing happens.

For this one and another, update your "using" directives:

using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;


4) Ok, how to remove the first object in the scene with particular name?

Here you go (use cautiously!):

[MenuItem("Tools/Remove object with name...")]
static void RemoveObjectWithName()
{
    GameObject[] rootGOs = 
    SceneManager.GetActiveScene().GetRootGameObjects();

    GameObject objectToRemove = null;

    foreach (GameObject go in rootGOs)
    {
        if (go.name == "Andrew")
        {
            objectToRemove = go;
            break;
        }
    }
    
    if(objectToRemove)
        UnityEngine.Object.DestroyImmediate(objectToRemove);
}

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

Python crash course part 10: inheritance and polymorphism

In the last part we've shown how to create and use a class in Python. Today we're going to talk about inheritance: wchich means cre...