- Home /
DropDown in Editor Inspector reset In play mode
I tryed to make dropdown in the inspector and saw this answer: https://answers.unity.com/questions/458987/dropdownlist-with-string-array-in-editor-inspector.html (the first one)
I've tryed it and somehow when I entered play mode all of the dropdowns in the scene has been changed back to the first index (index=0) why is this happening?
here is my code: **the script I want the dropdown in it called "GameTrigger" and the list called "TtriggerType "
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(GameTrigger))]
public class DropDownEditor : Editor
{
int dropDownIndex = 0;
string[] triggerType = new string[] {"activate", "summoning", "moving" };
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
dropDownIndex = EditorGUILayout.Popup(new GUIContent("Trigger Type"), dropDownIndex, triggerType);
var someClass = target as GameTrigger;
someClass.triggerTypeSelected = triggerType[dropDownIndex];
EditorUtility.SetDirty(target);
}
}
Answer by Hellium · Jun 11, 2019 at 11:48 AM
The problem comes from the fact that the instance of the class DropdownEditor
is destroyed when the focus on the gameObject holding your component is lost. A new instance is created when you focus the gameObject back, meaning the dropDownIndex
value gets its default value: 0.
So you have to find a way to retrieve the correct value when the gameObject is focused. A simple way is to change the default value of the index, and retrieve the value from the component when needed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor( typeof( GameTrigger ) )]
public class DropDownEditor : Editor
{
int dropDownIndex = -1;
string[] triggerType = new string[] {"activate", "summoning", "moving" };
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var someClass = target as GameTrigger;
if ( dropDownIndex < 0 )
dropDownIndex = Mathf.Max( System.Array.FindIndex( triggerType, type => string.Equals( type, someClass.triggerTypeSelected ) ), 0 );
dropDownIndex = EditorGUILayout.Popup( new GUIContent( "Trigger Type" ), dropDownIndex, triggerType );
someClass.triggerTypeSelected = triggerType[dropDownIndex];
EditorUtility.SetDirty( target );
}
}