- Home /
Properties not serializing properly
I am having the following problem.
For some reason Unity resets the values of properties in Play Mode or when the gameobject is made into a prefab.
In the example below t1 does not serialize properly whilst t2 does. Any idea what may cause the issue and how to fix it ?
[SerializeField] // this is needed otherwise t1 doesn't show up at all in the inspector
public TargetType t1{get; set; }
public TargetType t2;
As it didn't mentioned, Unity docs refer to fields as properties, which may cause the misconception that Unity can serialize c#'s properties.
Answer by taylank · Sep 10, 2018 at 07:17 PM
As far as I know auto-properties don't get serialized by Unity. You need a backing member for your get-set block. I'd go with:
[SerializeField]
private TargetType t1;
public TargetType T1 {
get {return t1;}
set {t1 = value;}
}
Thanks for the suggestion. If I do that I can see but not edit the property in the inspector. I have to add T1 = t1 inside the OnValidate method for it to work. This seems to me that it would make it very inconvenient to code to interfaces rather than classes as I had planned to do. Is that indeed a no go when working with Unity ? Even though interfaces are a great alternative to multiple inheritance not being possible in C#.
You shouldn't need that extra code in OnValidate for the above code to work. t1 should be visible and editable in the inspector. Are you sure you are not somehow applying some kind of ReadOnly attribute on t1? Or do you have a custom editor for your class?
As for interfaces, yeah Unity does not serialize them. Polymorphic serialization in general is a non starter in Unity.
Answer by Bunny83 · Sep 10, 2018 at 07:22 PM
Unity never supported serialization of properties. Only fields can be serialized. Attributes on auto properties belong to the property only. The implicit private backing field can't get any attributes. If you want to apply attributes to the backing field you can't use auto properties. So you have to implement the backing field yourself
[SerializeField]
private TargetType m_T1;
public TargetType t1
{
get {return m_T1;}
set {m_T1 = value;}
}
Keep in mind that Unity's serialization system directly serializes fields. That means when changing a value in the inspector you actually change the field. The setter of the property will not be called. Again, Unity does not serialize properties at all.