A controller for any Character script?

Hey,

I have a CharacterController, who’s sole purpose is to control a single character as if it was the main character. It could be a Dog, Cat, Unicorn, whatever - as long as it has a script that extends off of Character (a MonoBehaviour script), it’s golden.

The goal being to grab the script from within CharacterController.

public class CharacterController : MonoBehaviour
{
    [SerializeField] public GameObject character;
    [SerializeField] public Character script;

    void Start()
    {
        script = (Character) character.GetComponent(script.name);
    }

    private void Update()
    {
        Debug.Log(script.isGrounded);
    }
}

My solution right now is to reference the script through the Inspector. Let’s say I’m trying to pass a script called Dog into it. In the Start method, I grab the component called “Dog”, and I cast it to a “Character” script.

I really don’t like this solution, though. It just seems sketchy to me, and I’m not even sure if the “script.name” should ever be used. I feel like this may introduce errors down the road.

Is this solution solid, or are there better solutions for handing this kind of scenario?

private Character script; // no need to serialize this if it's overwritten anyway

void Start()
{
    script = character.GetComponent<Character>();
}

The GetComponent will return it as Character and it will work with scripts that extend that class.

EDIT: Only sketchy thing I saw was the serialized script, since it was immediately overwritten anyway and only used for its name. The name should not be needed anyway, if any character script is fine, as long as they extend Character.

That’s awesome, thanks! That’s so much better.