0

I'm setting up an inheritance system for my project in Unity using C#.

Entity : MonoBehaviour // Humanoid : Entity

I'm doing this so I can setup properties within each class type, specific to the type of mob it is within the game.

public class Entity : MonoBehaviour
{
    public Animator anim;
    public CapsuleCollider capsuleCollider;
    void Start()
    {
        anim = GetComponent<Animator>();
        capsuleCollider = GetComponent<CapsuleCollider>();
    }
}
public class Humanoid : Entity
{
    void Start()
    {
        capsuleCollider.radius = 0.3f;
    }
}

My issue is that the GameObject Humanoid is attached to won't run their Start() method after Entity's start method has run. It throws this error since they're trying to run at the same time:

UnassignedReferenceException: The variable capsuleCollider of NPC has not been assigned.

So I'm unsure how to hook into (I believe that's the correct terminology) the end of my Entity's Start() method with my Humanoid's Start() method.

I could change Entity's start to Awake() and that might fix my problem, but I want to setup multiple levels of inheritance so that wouldn't work between all of them.

2
  • Maybe virtual? Not sure if it is supported for “start” in Unity Commented Mar 29, 2020 at 21:01
  • Trying it now, but no luck. I could be calling it wrong though, I'll keep trying. Commented Mar 29, 2020 at 21:05

1 Answer 1

3

I believe what you are referring to is a Object Orientated Programming concept called Polymorphism. C# supports this with keywords such as virtual and override. Documentation for Polymorphism in C# can be found here. I have provided an example below:

public class Entity : MonoBehaviour
{
    public virtual void Start()
    {
        // ... code specific to Entity
    }
}

public class Humanoid : Entity
{
    public override void Start()
    {
        base.Start(); // Do Entity.Start() first, then continue with Humanoid.Start()

        // ... other code specific to Humanoid
    }
}

I do not know if the Unity Engine supports this; I would presume so.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! This is exactly what I needed, thank you. I had tried this but called it wrong. Your resource is appreciated, I'll be reading it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.