- Home /
How can I add a parameter to a button in a custom editor?
I've created a button in a custom editor script that is associated with a class containing a serialized array of Transforms
. I am wondering if it's possible to associate the button with a certain index in that array from the inspector; right now I have to go into my code to change which prefab is used in my DoSomething(Transform item)
method.
Here is an example case:
[CustomEditor(typeof(TestClass))]
public class TestClassEditor : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("Do Something"))
{
var test = target as TestClass;
test.DoSomething(test.MyPrefabs[0]); //I have to update this index via code
}
}
}
public class TestClass : Monobehavior
{
public Transform[] MyPrefabs { get { return myPrefabs; } }
[SerializeField]
private Transform[] myPrefabs;
public void DoSomething(Transform item)
{
//do something
}
}
To be clear, my ideal scenario is to have some sort of dropdown menu next to the "Do Something" button in the inspector that contains all of the possible indices of the myPrefabs
array. I would then be able to select a certain index, and that index would be passed to the DoSomething(Transform item)
method in the custom editor script.
I'm pretty new to making my own editor scripts, so any help is very much appreciated.
Answer by WarmedxMints · Mar 19, 2019 at 03:59 AM
You can get the names of the transforms and EditorGUILayout has a popup method which you can populate with those names and the popup will return an int which will give you your index.
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(TestClass))]
public class TestClassEditor : Editor
{
private TestClass _test;
private int _index;
public void OnEnable()
{
_test = (TestClass)target;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var enable = _test.MyPrefabs != null && _test.MyPrefabs.Length > 0;
if (enable)
{
var names = GetNames();
EditorGUILayout.Space();
_index = EditorGUILayout.Popup(_index, names);
EditorGUILayout.Space();
if (GUILayout.Button("Do Something with " + names[_index]))
{
_test.DoSomething(_test.MyPrefabs[_index]); //I have to update this index via code
}
}
else
{
EditorGUILayout.LabelField("MyPrefabs is empty");
}
}
private string[] GetNames()
{
var count = _test.MyPrefabs.Length;
var ret = new string[count];
for(var i = 0; i < count; i++)
{
ret[i] = _test.MyPrefabs[i].name;
}
return ret;
}
}
#endif
public class TestClass : MonoBehaviour
{
public Transform[] MyPrefabs { get { return _myPrefabs; } }
[SerializeField]
private Transform[] _myPrefabs;
public void DoSomething(Transform item)
{
//do something
}
}