PropertyDrawer, Change property within callback

I write a custom property drawer for Enum type. I need to draw categorized dropdown menu instead of regular enum dropdown (using GenericMenu type).

GenericMenu uses callback function to apply menu item selection. Instead of regular function I use lambda expression to keep current scope (and to use current property reference).
The problem is, that I change property.intValue to set newly selected enum, but this changes is not saved.

My code:

public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
	EditorGUI.BeginProperty(position, label, property);

    //ItemType is referenced enum
	var curretnType = (ItemType)property.intValue;

	if (GUI.Button(position, curretnType.ToString(), EditorStyles.toolbarButton))
	{
		ItemEntry[] entries = ... // basically represent all enum entries of ItemType enum with some extra data

		GenericMenu toolsMenu = new GenericMenu();
		foreach (ItemEntry entry in entries)
		{
			string path = ...
			ItemType entrtType = entry.Type;
			toolsMenu.AddItem(new GUIContent(path), false, () =>
			{
				property.intValue = (int)entrtType;
				Debug.Log(property.intValue);
			});
		}
		toolsMenu.ShowAsContext();
	}

	EditorGUI.EndProperty();
}

Debug.Log shows, that correct value is setted, but this “curretnType” I use as a lable for a button is not chnaging.

How can I cache current property to change it’s values outside OnGUI method?

Thanks!

Hi there,

It’s probably a problem with the script where you actually call this drawer:
So you have a script with a line of code containing something like this:

EditorGUI.PropertyField( yourRect, yourSerializableObject.FindProperty(YourProperty));

Right?
Before this line you need to call:

yourSerializableObject.Update();

And afterwards you need to call this:

yourSerializableObject.ApplyModifiedProperties();

So in total it looks like this:

yourSerializableObject.Update();
EditorGUI.PropertyField( yourRect, yourSerializableObject.FindProperty(YourProperty));
yourSerializableObject.ApplyModifiedProperties();

I hope this helps!

-Gijs

Well, I don’t know what caused this strange issue (and hope I’ll find explanation eventually), but to make this work now I use private variable

private int _newValue = -1;

in the callback function I set it to new enum value

toolsMenu.AddItem(new GUIContent(path), false, 
    () => _newValue = (int)entryType);

and at the end of OnGUI method:

if (_newValue > 0)
{
	property.intValue = _newValue;
	_newValue = -1;
}

My Enum starts from 1 so it works fine