Im trying to write a property drawer where one can select a serialized reference, but I can’t get the selection to stick. I’ve whittled it down to the smallest example, and I can’t figure out where Im going wrong…
The object I wish to serialize:
[Serializable]
public class ReferenceType
{
public ReferenceType() { this.name = "Nothing"; }
public ReferenceType(string name) { this.name = name; }
public readonly string name;
}
The Mono that is referencing it:
public class ReferenceTester : MonoBehaviour
{
[SerializeReference]
ReferenceType refType;
void Update()
{
Debug.Log("Type is " + refType.name + ". Should be Something");
}
}
The Property Drawer:
[CustomPropertyDrawer(typeof(ReferenceType))]
public class ReferenceTypeDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
property.serializedObject.Update();
if (property.managedReferenceValue == null
|| ((ReferenceType)property.managedReferenceValue).name != "Something")
property.managedReferenceValue = new ReferenceType("Something");
property.serializedObject.ApplyModifiedPropertiesWithoutUndo();
}
}
When I click play, the editor displays:
HOWEVER, while playing, if select the game object to inspect it, the log changes to:
It will stay the proper value until I run the game again, at which point the problem repeats.
Anyone have any advice?