Home > Enterprise >  Best practice for an optional method that I want to call in Start()?
Best practice for an optional method that I want to call in Start()?

Time:08-20

I've created an abstract class called PlayerComponent for all components that need to interact with my PlayerController to inherit from. This class holds the reference to the PlayerController, the Player (responsible for input), and I wanted to add a bit of functionality by setting up a method to trigger when the PlayerController "lands" on the ground.

public abstract class PlayerComponent : MonoBehaviour
{
    protected static PlayerController playerController;
    protected Player player; //the Rewired player

    protected void Start()
    {
        player = ReInput.players.GetPlayer(0);

        if (playerController == null)
            playerController = FindObjectOfType<PlayerController>();

        playerController.onLanding.AddListener(OnPlayerLanding);
    }

    public abstract void OnPlayerLanding();
}

In Start(), I subscribe an abstract method to the UnityEvent that the PlayerController invokes upon landing. It works great and I quite like how I've structured this, but in practice, I ended up creating some PlayerComponents that don't need the OnPlayerLanding method at all. Since its an abstract method, these PlayerComponents are required to have this blank method sitting there, and possibly taking up resources by being invoked (idk if that's even true, is it?). Is there a best practice for how I can make this method optional? Should I make an additional class to act in between the 2 which is responsible for making the Landing calls, and have only the components that require it inherit from it? I'm a little out of my comfort zone but trying to learn how to do this nice and tidy.

CodePudding user response:

Make method by virtual, and override it for need in heir.


    public abstract class SomeClass : MonoBehaviour
    {
        public virtual void Start()
        {
            // Base code
        }

        public virtual void Mehtod()
        {
            //
        }
    }

Make Start() virtual too. To call the method where necessary, override Start() with the base implementation and complete the subscription

public abstract class SomeHeir : SomeClass
    {
        protected static PlayerController playerController;

        public override void Start()
        {
            base.Start();

            playerController.onLanding.AddListener(OnPlayerLanding);
        }
    }

You can virtualize all MonoBenaviour methods

  • Related