Values set in default Inspector reset on Play

Hello

I have a class SightZone like this :

[Serializable]
public class SightZone 
{
    [SerializeField, RangeStep(20, 360, 10)]
    public int fieldOfVision;

    [SerializeField, Range(0.01f, 20f)]
    public float lineOfSight;

    [SerializeField, Range(minPrecisionRange, maxPrecisionRange)]
    public int precision;

    [SerializeField]
    private Material sightZoneMaterial;

    [SerializeField]
    public bool reshapable;

    public SightZone(Transform _parentTransform, Vector3 _offsetY) {}
}

With public properties for the Serialized. (The RangeStep attribute is a custom one and is working fine … normaly)

I use this class in :

public abstract class EnemyBehaviour : MonoBehaviour
{
    [SerializeField]
    protected SightZone sightZone;
    
    protected virtual void Awake()
    {
        // Some Code
        sightZone = new SightZone(transform, offsetY);
    }
}

Before, I was making everything SightZone is making directly in the EnemyBehaviour class and it was working. But know when I press Play, every SerializeField of SightZone are reset.

I haven’t done a custom Inspector, but on another case I had it was working fine.

Thanks for any Help !

The problem is that the sightZone field has already been deserialized (using the data you configured in the inspector) by the time you get to Awake. When you assign a new value to it, you are wiping out all of those data.

You should either (1) put a null guard around that line or (2) assign a default instance in the field initializer.

// option 1
protected virtual void Awake() {
    if (sightZone == null)
        sightZone = new SightZone(transform, offsetY);
}

// option 2
[SerializeField]
protected SightZone sightZone = new SightZone();