Assign enum value to serialized property from EditorGUI.EnumFlagsField

EditorGUI.EnumFlagsField seems to work pretty well for obtaining a value, but I’m having trouble assigning that value back to the serializedproperty. SerializedProperty.enumValueIndex setter doesn’t work, it prints a enum index is out of range error if the value is greater than the number of defined values in the enum. So how can I set the proper value through a serialized property?

using UnityEngine;

using UnityEditor;

public class TestObjectEditor : PropertyDrawer
	public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
		var alignmentProperty = property.FindPropertyRelative("alignment");
		var value = (int) (Alignment) EditorGUI.EnumFlagsField(position, alignmentProperty.displayName, (Alignment) alignmentProperty.enumValueIndex);
		alignmentProperty.enumValueIndex = value; // Error with any value > number of defined values in the enum
		if (EditorGUI.EndChangeCheck())

public class TestObject : ScriptableObject
	public TestDrawer testDrawer;

public class TestDrawer {

	public Alignment alignment;

public enum Alignment
	TopLeft = 1 << 0,
	TopCenter = 1 << 1,
	TopRight = 1 << 2,
	MiddleLeft = 1 << 3,
	MiddleCenter = 1 << 4,
	MiddleRight = 1 << 5,
	BottomLeft = 1 << 6,
	BottomCenter = 1 << 7,
	BottomRight = 1 << 8,

The “enumValueIndex” (as the name suggests) is an index value. It actually selects a single enum element out of SerializedProperty.enumNames. Since your field looks like it should be a bitmask you want to assign the actual bitmask value to SerializedProperty.intValue.

Though to me your enum looks a bit strange. The point of a bitmask is to allow any combination of the given elements. Since your elements do already have “logical overlaps” it seems like a bit misused. When do you need a combination of TopLeft and MiddleCenter for example? Or what does TopLeft + TopCenter mean?

If you actually just want a value that is representing one of the 9 alignment combinations you have there you don’t want to use a bitmask at all. You have 9 distinct values. So you would simply use an EnumPopup to select a single value.