Serialise inherited virtual varaible

Hi Guys,

I have an abstract class with an object called ‘anchor’, which child objects automatically attach to.

The anchor I want to set in the inspector, according to the object inheriting the class. However I don’t know how to make the variable visible in the editor, while having it inherited from an abstract class. Ideally I’d want something like this that works:

Abstract Class

public abstract class MapBaseObject : MonoBehaviour {

    public virtual bool bInitialised { get; set; }
    [SerializeField]
    public virtual GameObject anchor { get; set; }

    public void Start()
    {
        Initialise();
    }

    public void FixedUpdate()
    {
        if(bInitialised)
        {
            transform.position = (anchor.transform.position + new Vector3(0, 0, -0.1f));
        }
    }

    public virtual void Initialise()
    {
        SetAnchorPosition();
    }

    public virtual void SetAnchorPosition()
    {

    }
}

Class inheriting abstract…

public class MapObjPlayer : MapBaseObject
{
    public override void Initialise()
    {
        base.Initialise();
    }

    public override void SetAnchorPosition()
    {
        transform.position = GridReference.GetRandomMapPosition(GameObject.FindGameObjectWithTag("Map"));

        bInitialised = true;
    }
}

Any idea guys?

Thanks!

You can’t serialize a property, you can only serialize fields. Auto-properties are serialization death because you can’t even access the backing field properly. This will work just fine, though:

public abstract class MapBaseObject : MonoBehaviour
{
    [SerializeField]
    private bool _bInitialized;

    public virtual bool bInitialised
    {
        get { return this._bInitialized; }
        set { this._bInitialized = value; }
    }

    [SerializeField]
    private GameObject _anchor;

    public virtual GameObject anchor
    {
        get { return this._anchor; }
        set { this._anchor = value; }
    }

    public void Start()
    {
        Initialise();
    }

    public void FixedUpdate()
    {
        if (bInitialised)
        {
            transform.position = (anchor.transform.position + new Vector3(0, 0, -0.1f));
        }
    }

    public virtual void Initialise()
    {
        SetAnchorPosition();
    }

    public virtual void SetAnchorPosition()
    {

    }
}

Also, I know this was just a quick and dirty example, but if you have a method with no implementation like SetAnchorPosition here, you can just set it to abstract instead and force all inheriting classes to write their own implementation of it.

1 Like

Awesome thanks Lysander, you should get paid for this stuff lol