简体   繁体   中英

C# Multi-Level Inheritance - Same methods

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.

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.

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