Unity重写了一个虚方法,并在if中添加了一条语句



我有一个问题,我有3个类,一个是基类,另外两个继承它,基类有一个带有计数器的方法,如果时间用完,它应该销毁gameObject,但是其他类应该有这个方法但是在这个条件语句中你可以添加任何东西我只是想从另一个类中给它添加一个额外的命令。

如果你不明白,尽管问,因为我不擅长解释。

public class A : MonoBehaviour
{

public virtual void DestroyByTime()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
{
/*
This statement should only be added in class B
|
v
gameSession.GameOver();
*/


Destroy(gameObject);
}
}

private void Update()
{
DestroyByTime();

}
}
public class B : A
{

public override void DestroyByTime()
{

/*

I want the base class if to be saved, but in if statement time runs out you lose
(gameSession.GameOver())
*/
}
}

您只能在派生类中创建一个覆盖的OnTimeOut方法:

public class A : MonoBehaviour
{
public virtual void DestroyByTime()
{
timeLeft -= Time.deltaTime;
if (timeLeft <= 0)
{
OnTimeOut();

Destroy(gameObject);
}
}
protected virtual void OnTimeOut()
{
// Do nothing here
}
private void Update()
{
DestroyByTime();            
}
}
public class B : A
{
protected override void OnTimeOut()
{
gameSession.GameOver();
}
}

相关内容

最新更新