我的继承逻辑需要帮助。
这是我的项目结构:(所有脚本都在“播放器”(预制对象)上
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/