Search code examples
c#unity-game-engineunity-editor

Unity Custom Editor GUI


screenshot

I'm having an issue adding new values in fields after they are created in Editor, they keeping coming back and if i enter a new one it will display the first value. Can anyone give me snippet of code how can i add values which will be automatically saved.

Thanks!

    GUILayout.BeginHorizontal();
    GUILayout.BeginVertical();
    addInteger = GUILayout.Toggle(addInteger, "Integers");
    howMuchIntegers = EditorGUILayout.IntField(howMuchIntegers);
    intNames = new string[howMuchIntegers];
    if (addInteger)
    {
        if (howMuchIntegers != 0)
        {
            GUILayout.BeginVertical("box");
            for (int i = 0; i < howMuchIntegers; i++)
            {
                intNames[i] = i.ToString();
                intNames[i] = EditorGUILayout.TextField(intNames[i]);
            }
            GUILayout.BeginVertical("box");
        }
    }
    GUILayout.EndVertical();
    GUILayout.EndHorizontal();

Solution

  • I think your data is getting overwritten in 2 places.

    Here,

    intNames = new string[howMuchIntegers];
    

    and here,

    intNames[i] = i.ToString();
    

    So here is one solution. Basically I just suggest that you extract the parts that don't need to be run 60 times a second, you can do this however you want.

     bool firstTimeRun = true;
    
     void OnGUI()
     {    
        GUILayout.BeginHorizontal();
        GUILayout.BeginVertical();
        addInteger = GUILayout.Toggle(addInteger, "Integers");
        howMuchIntegers = EditorGUILayout.IntField(howMuchIntegers);
    
        if(firstTimeRun)
        {
            intNames = new string[howMuchIntegers];
            if (addInteger)
            {
                if (howMuchIntegers != 0)
                {
                    GUILayout.BeginVertical("box");
                    for (int i = 0; i < howMuchIntegers; i++)
                    {
                        intNames[i] = i.ToString();
                        intNames[i] = EditorGUILayout.TextField(intNames[i]);
                    }
                    GUILayout.BeginVertical("box");
                }
            }
    
            firstTimeRun = false;
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
        }
        else
        {
            if (addInteger)
            {
                if (howMuchIntegers != 0)
                {
                    GUILayout.BeginVertical("box");
                    for (int i = 0; i < howMuchIntegers; i++)
                    {
                        intNames[i] = EditorGUILayout.TextField(intNames[i]);
                    }
                    GUILayout.BeginVertical("box");
                }
            }
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();
        }
     }