简体   繁体   English

C# 多级继承 - 相同的方法

[英]C# Multi-Level Inheritance - Same methods

I'm setting up an inheritance system for my project in Unity using C#.我正在使用 C# 在 Unity 中为我的项目设置继承系统。

Entity : MonoBehaviour // Humanoid : Entity实体:MonoBehaviour // 人形:实体

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.我的问题是,在实体的 start 方法运行后,附加的 GameObject Humanoid 不会运行它们的 Start() 方法。 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.因此,我不确定如何使用 Humanoid 的 Start() 方法挂钩(我认为这是正确的术语)实体的 Start() 方法的末尾。

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.我可以将 Entity 的 start 更改为 Awake() ,这可能会解决我的问题,但我想设置多个继承级别,这样就无法在所有级别之间工作。

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. C# 通过 virtual 和 override 等关键字支持这一点。 Documentation for Polymorphism in C# can be found here .可以在此处找到 C# 中的多态性文档。 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;不知道Unity Engine是否支持; I would presume so.我会这么认为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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