c# - 继承逻辑 : PlayerBase and Player scripts childs

标签 c# unity3d structure

我的继承逻辑需要帮助。

这是我的项目结构:(所有脚本都在“播放器”(预制对象)上

PlayerBase : MonoBehaviour
{
    //Some props
    public Color Color {get; set;}

    void Start()
    {
        Color = Color.Red;
    }
}   

PlayerLife : PlayerBase
{
    void Start()
    {
        Cube.Color = base.Color;
    }
}   


PlayerController : PlayerBase
{
    void Start()
    {
        Foo.Color = base.Color;
    }
}

正如我所看到的,childs Start 在我的 parent 开始之前被初始化。 因此,Color 为空(alpha 为 0 的黑色)。

我如何使用我 parent 的属性,在他的 start() 中为我的子类初始化?

(我的第一个解决方案是:在 PlayerBase 中创建一个函数来初始化我的颜色,如下所示:

protected void InitColor()
{
    Color = Color.red;
}

在我的 child 类(class)中,每次需要时我都会调用这个函数。

很烂,不合逻辑。因为对于 PlayerBase 类,颜色仍然是黑色 (null))

你能帮帮我吗?

谢谢

最佳答案

你可以做的是在子类中使基类方法虚拟覆盖,然后在子类中你可以调用Start 使用 base.Start() 实现基类的方法,以便在执行子实现之前执行基类代码实现:

PlayerBase : MonoBehaviour
{
    //Some props
    public Color Color {get; set;}

    protected virtual void Start()  // make it virtual so childs can override
    {
        Color = Color.Red;
    }
}   

PlayerLife : PlayerBase
{
    override void Start()
    {
        base.Start();    // call first base class implementation
        Cube.Color = base.Color;
    }
}   


PlayerController : PlayerBase
{
    override void Start()
    {
        base.Start();    // call first base class implementation
        Foo.Color = base.Color;
    }
}

关于c# - 继承逻辑 : PlayerBase and Player scripts childs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41265373/

相关文章:

c# - Socket.SendAsync 需要几秒钟才能完成

c# - C# 中的 Excel - 2 张纸有问题

c# - 自定义随机数生成器

c - C中的结构大小

c - 从文件中读取数据

c# - VS远程调试问题

audio - Unity3D-如何使纹理更改静音按钮/切换?

c# - 在Unity中使用启动画面时是否可以发出声音?

c - 这段代码中union的意义是什么,structure的缺点是什么?

c# - 如何跟踪 LUIS 服务的每个最终用户的配额使用情况?