简体   繁体   中英

Unity OnDisable - can I virtual override the built in unity methods?

Is it possible to use virtual void OnDisable()? Its a built in Unity method, just like Start() or OnEnable(). I couldnt find any resources online where its explained if we can use virtual on these built in methods.


    public abstract class ShipComponent : MonoBehaviour
    {
    [HideInInspector] public ShipControl shipControl;

    public virtual void Init(ShipControl control)
    {
        this.shipControl = control;
        StartCommonCoroutines();
    }
    public virtual void IsPlayer()
    {
        SetListeners();
        StartPlayerOnlyCoroutines();
    }
    public virtual void OnEnable()
    {
        StartCommonCoroutines();

        if (!shipControl.shipWrapper.ship.IsPlayer) return;
        SetListeners();
        StartPlayerOnlyCoroutines();
    }

    public virtual void OnDisable()
    {
        RemoveListeners();
        StopAllCoroutines();
    }

    public abstract void SetListeners();
    public abstract void RemoveListeners();

    public abstract void StartCommonCoroutines();

    public abstract void StartPlayerOnlyCoroutines();
    public abstract void StopPlayerOnlyCoroutines();

}

I want to Inherit from ShipComponent in subclasses and whenever a subclass that inherits from ShipComponent calls OnDisable() (Unity built in version) then I want it to call the baseClass' ShipComponent.OnDisable() as initialized above.

I realize OnDisable() is a built in method, so should I instead be doing:

public override void OnDisable()
{
    base.OnDisable();
    RemoveListeners();
    StopAllCoroutines();
}

Because we are overidding the original built in Unity method this way?

Thanks.

Unity does a little bit of reflection magic on user scripts, and it creates internal list of MonoBehaviours that have OnEnable/OnDisable methods - it calls them even if they are private, and you don't need to explicitly implement any interface for this to work.

This also means that it does not care if the method is virtual or not, it will call a correct override if you override it in your inheriting classes.

Do not mark it as override in your base class as there is no base implementation in MonoBehaviour itself. I would assume this decision was made for performance reasons - if all objects had those methods, even if they were empty, they would have to be called. If there are no methods, its a few calls less.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM