Software7

Personal Developer Notebook

Simple Unity Editor Scripting Example with a PopUp

Sometimes you want to make a bunch of changes in Unity at once. A great feature of Unity is that you can easily extend the Editor itself by a script.

The following simple example adds a new editor window with a popup. When one or more Transforms are selected you can apply the Z-values of these Transforms to a few predefined values from the popup at once.

Custom Unity Editor Window

Custom Unity Editor Window

Instructions:

  • if you don’t have a folder ‘Editor’ in Unity’s Assets folder create one
    (it must be called ‘Editor’!)

  • place the following script into this folder

  • it’s important to note that the name of the .cs must be the same as the class name (here MyEditorWindow), otherwise you will see the following error:

    _NullReferenceException: Object reference not set to an instance of an object

_ when calling GetWindow()

using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

class MyEditorWindow : EditorWindow
{
     private string[] options = new string[] {"0.1", "0.2", "0.3"};
     private int index = 0;

    [MenuItem ("Examples/ApplyZ")]

    static void Init ()
    {
        MyEditorWindow window = (MyEditorWindow)EditorWindow.GetWindow (typeof (MyEditorWindow));
    }

    void OnGUI()
    {
        index = EditorGUILayout.Popup(index, options);
        if(GUILayout.Button("Apply"))
            Apply();
     }

     void Apply()
     {
        float newZ = float.Parse(options[index]);

        if(Selection.transforms.Length == 0)
            EditorUtility.DisplayDialog("No Selected Transforms", "To use ApplyZ you have to select one or more Transform", "Ok");

        foreach (Transform oneTrans in Selection.transforms) {
            Vector3 pos = oneTrans.position;
            oneTrans.position = new Vector3(pos.x, pos.y, newZ);
        }
     }
}