Backing field serialized despite using [NonSerialized]

Despite using [NonSerialized] on a member that deliberately hides another with the same name from the parent class, I get the occasional editor error message that unity is trying to serialize the same field twice. Specifically The same field name is serialized multiple times in the class or its parent class. This is not supported: Base(OnThingSelected) <assignedEffect >k__BackingField Shouldn’t the field not be serialized, or even have a backing field to serialize, and why not throw the error for OnThingSelected as it’s using the same behavior.

It’s likely I’m breaking a few polymorphism rules here, but without some major refactoring of the related systems I was hoping to just override the member.

Simplified example for clarity:

public class ThingLogics : MonoBehaviour {
    public enum PhysicalEffect {
        None,
        Burn,
        Freeze,
        Acid
    }
    public enum VisualEffect {
        None,
        Sparkle,
        Shine
    }
//More stuff
}

public class ThingUI : MonoBehaviour {
    [NonSerialized]//Assigned during generation by factory
    public Action<ThingLogics.PhysicalEffect> OnThingSelected;
    [NonSerialized]//Assigned during generation by factory
    public ThingLogics.PhysicalEffect assignedEffect = ThingLogics.PhysicalEffect.None;
}
public class PrettyThingUI : ThingUI {
    [NonSerialized]//Assigned during generation by factory
    public new Action<ThingLogics.VisualEffect> OnThingSelected;
    [NonSerialized]//Assigned during generation by factory
    public new ThingLogics.VisualEffect assignedEffect = ThingLogics.VisualEffect.None;
}

OnThingSelected is not affected because Unity doesn’t support serializing delegates.

Not sure what’s happening with assignedEffect, maybe Unity checks and generates the error before the NonSerialized attribute is taken into consideration? I would try to create a simple repro project and then report it as a bug.

But I suspect the error is caused by the shadowing (new). This effectively creates two assignedEffect fields, one in the base class and one in the derived class, which trips up Unity.

Shadowing is pretty unusual, are you sure you want to shadow and not use a property with virtual/override (properties aren’t serialized so that would remove the need for NonSerialized)?
Or just let the factory assign the fields and not shadow/override them at all? From the code you’ve posted, it’s not clear why that’s necessary.

2 Likes