- Home /
Property drawer using a field's method on a button
Hello!
I have made a custom dictionary class. I would like it to have a "validate" button with each Dictionary. This would run a method on demand that checks the dictionary for duplicates, empty entries, etc.
I am getting a null exception because serializedObject.targetObject is referring to my SaveScriptEditor, while my field expects it to be looking at my dictionary class called "floatDictionaryP". I'm sure I am missing the proper way to do this with properties and fieldInfo, but I've been at it for hours and can't figure it out.
var obj = fieldInfo.GetValue(_dict.serializedObject.targetObject);
Debug.Log("Found field info of " + obj);
DictionaryPairBase myDataClass = obj as DictionaryPairBase;
if (obj.GetType().IsArray)
{
var index = Convert.ToInt32(new string(property.propertyPath.Where(c => char.IsDigit(c)).ToArray()));
myDataClass = ((DictionaryPairBase[])obj)[index];
}
myDataClass.CleanEntries();
So I am wondering, what is the proper syntax to refer to my nested property? (the serializedObject.targetObject's floatDictionaryP)
Is this the proper approach for making a validate button that will always appears with my dictionaries?
Answer by Bunny83 · Dec 15, 2018 at 11:48 AM
PropertyDrawers are not meant to work with actual objects at all. The whole inspector works only on the abstracted serialized data of your classes. So you don't have direct access to object instances. Also note that "_dict.serializedObject.targetObject" can only refer to the topmost UnityEngine.Object derived type which is usually either a MonoBehaviour or a ScriptableObject.
There are some hacky ways to get access to the class instances you're looking for, however this usually isn't the way to go. With SerializedObject / SerializedProperty you can actually inspect several instances at once since Unity has added multi object editing. So when writing property drawers you should always keep the hasMultipleDifferentValues field in mind.
If you want to keep using a propertydrawer first you should make sure you handle multi editing propertly. Since editing a dictionary from two different object at once doesn't really work unless they are the same you probably want to not view your UI when there are multiple different values.
With a propertydrawer you generally have two options:
manually use reflection (like in the hacky post i've linked above) and figure out the actual object instance this serialized property belongs to
Implement the validation method inside your propertydrawer and work through the SerializedProperties.
The second solution is probably the better one that has a higher chance to be compatible with future Unity versions.
Thank you so much for your answer. It is very clear and detailed. I have a better idea of property drawer's limitations and usage now.
Your answer
![](https://koobas.hobune.stream/wayback/20220612183941im_/https://answers.unity.com/themes/thub/images/avi.jpg)