当分数达到时如何增加生命值



我正在做一个无休止的跑步游戏。并希望在达到一定分数时增加健康/生命。在附加到 ScoreManager 的 ScoreManager 脚本中,我有:

public class ScoreManager : MonoBehaviour
{
public int score;
public Text scoreDisplay;
bool one = true;
Player scriptInstance = null;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
}
}
// Start is called before the first frame update
void Start()
{
GameObject tempObj = GameObject.Find("ghost01");
scriptInstance = tempObj.GetComponent<Player>();
}
// Update is called once per frame
private void Update()
{
scoreDisplay.text = score.ToString();
if (scriptInstance.health <= 0)
{
Destroy(this);
}
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
}

我使用以下行来增加里程碑的运行状况,但必须无休止地复制代码以创建多个里程碑。

if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}

我的问题是如何在不重复代码的情况下每 75 点增加一次生命值?

if(score % 75 == 0)这样的模的问题在于它在score == 75时一直返回true..所以无论如何它都需要一个额外的bool标志。

我宁愿为此简单地添加第二个计数器!

并且根本不要在Update中反复检查内容,而是在设置它的那一刻:

int healthCounter;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
Debug.Log(score);
// enough to update this when actually changed
scoreDisplay.text = score.ToString();
healthCounter++;
if(healthCounter >= 75)
{
scriptInstance.health++;
// reset this counter
healthCounter = 0;
}
}
}

一个缺点可能是知道无论在哪里重置score = 0都必须重置healthCounter = 0......但是您还必须对任何标志解决方案执行相同的操作;)

我会选择%运算符

private bool scoreChanged = false;
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Obstacle"))
{
score++;
scoreChanged = true;
Debug.Log(score);
}
}
if (score % 75 == 0 && scoreChanged)
{
scriptInstance.health++;
scoreChanged = false;
}

最新更新