Unity Editor scripting Error : Creating a dropdown

First day in UnityEditor scripting and after having some success with easy stuff (adding a button and creating a [ReadOnly] attribute for variables to be shown in inspector but not be modifiable), I tried to create a dropdown, and then, the problems started.

Here is the code I use :

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(GameController), editorForChildClasses: true)]
public class GameControllerEditor : Editor
{
    string[] myInputsName;
    int _myIndex = 0;

    public override void OnInspectorGUI()
    {       

        base.OnInspectorGUI();       

        GameController e = (GameController)target;

        for (int i = 0; i < e.inputType.Length - 1; i++)
        {
            myInputsName[i] = e.inputType[i].name;
        }
       
        _myIndex =  EditorGUILayout.Popup(_myIndex,myInputsName, EditorStyles.popup);

        if (GUILayout.Button("Switch Control"))
            e.SwitchControl();
    }
}

inputType is an array of a custom ScriptableObject.

After compiling the code it looks okay as it show me the drop box :

6777173--783881--upload_2021-1-28_23-8-47.png

First problem :
The dropdown is empty and it should have “Keyboard” in it.

Second problem :
If I focus on another asset and then I come back to it, the dropdown disapear and I got an error :
6777173--783890--upload_2021-1-28_23-10-59.png

Any idea, tips to solve that ?

Looks like you never initialilzed “myInputsName”. (You tried to assign values to particular elements of the array, but you never created the array itself.)

1 Like

Whenever you see Null Reference error, the answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Indeed, that’s what you do when you focus too long on something new…you search error in the new thing and forget to back to basis !

Thanks both of you :slight_smile:

1 Like