- Home /
How to handle this case: elements inside an array has a CustomPropertyDrawer?
The situation is like one that described in this thread
It says
On the plus side, elements inside arrays and lists do work with PropertyDrawers. For example, this will make every float in the array be displayed as a slider from 0 to 10:
Which is great, but what if each element needs it's own variable?
For example I have the following:
// the class to be custom drawn
class MyClass
{}
// this component has a array my custom drawn class
class MyMono : MonoBehaviour
{
public MyClass[] mcs;
}
// all elements in the array share one instance of property drawer
[CustomPropertyDrawer(typeof(MyClass))]
public class MyClassPropertyDrawer : PropertyDrawer
{
private int index = 0;
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
index = EditorGUI.Popup(position, index, new string[] { "1", "2", "3" }); // **problem here**
}
}
The problem is that for each element in mcs
, it calls OnGUI()
1 time; since there is only 1 MyClassPropertyDrawer
instance, index
is being shared; the result is that all popups has the same index (e.g. if you adjust the first popup, all the other popups change to the same index)
I can fix it using a List<int>
to store indexes for each element, and implement some check logic to give each element its own index, (see below) but I'd like to know if there is an official way to handle this case?
Thanks.
P.S. The method I use to solve the problem right now, but I think there should be a more general solution.
[CustomPropertyDrawer(typeof(MyClass))]
public class MyClassPropertyDrawer : PropertyDrawer
{
private List<int> indexes = new List<int>();
public override void OnGUI (Rect position, SerializedProperty property, GUIContent label)
{
int myIndex = GetMyIndex(property);
indexes[myIndex] = EditorGUI.Popup(position, indexes[myIndex], new string[] { "1", "2", "3" });
}
}
Answer by HarshadK · Jul 16, 2015 at 06:24 AM
If the index
is actually stored in your MyClass
then you can simply use the SerializedProperty
passed to the OnGUI()
method to access the index
value using SerializedProperty.intValue.
Something like:
property.FindPropertyRelative("index").intValue = EditorGUI.Popup(position, property.FindPropertyRelative("index").intValue, new string[] { "1", "2", "3" });
Haven't tested the code but you get the point.
Your answer
Follow this Question
Related Questions
How to prevent overlap when using nested arrays in CustomPropertyDrawers? 1 Answer
EditorGUI.IntField always 0 after GameStart 0 Answers
Custom Editor/Custom Property Drawer combo, breaks Enable button 1 Answer
JsonUtility not working with Arrays 2 Answers
How do I assign 3 variables to every GameObject in the array "enemy"? 2 Answers