【问题标题】:C# Multi-Level Inheritance - Same methodsC# 多级继承 - 相同的方法
【发布时间】:2020-03-29 20:57:04
【问题描述】:

我正在使用 C# 在 Unity 中为我的项目设置继承系统。

实体:MonoBehaviour // 人形:实体

我这样做是为了在每个类类型中设置属性,具体到它在游戏中的生物类型。

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;
    }
}

我的问题是,在实体的 start 方法运行后,附加的 GameObject Humanoid 不会运行它们的 Start() 方法。它会抛出此错误,因为它们试图同时运行:

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

所以我不确定如何使用 Humanoid 的 Start() 方法连接(我相信这是正确的术语)我的 Entity 的 Start() 方法的结尾。

我可以将 Entity 的 start 更改为 Awake(),这可能会解决我的问题,但我想设置多个继承级别,这样就不会在所有级别之间起作用。

【问题讨论】:

  • 可能是虚拟的?不确定 Unity 中是否支持“开始”
  • 现在尝试,但没有成功。不过我可能说错了,我会继续努力的。

标签: c# class unity3d inheritance


【解决方案1】:

我相信您所指的是一个称为多态的面向对象编程概念。 C# 使用 virtual 和 override 等关键字支持这一点。 C# 中的多态性文档可以在 here 找到。我在下面提供了一个示例:

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
    }
}

我不知道Unity引擎是否支持这个;我想是的。

【讨论】:

  • 是的!这正是我需要的,谢谢。我试过这个,但说错了。感谢您的资源,我现在会阅读它。
猜你喜欢
  • 2015-03-20
  • 2011-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多