分数达到时如何增加健康

How to increase health when score has reached

我正在制作一款无尽的跑酷游戏。并且想在达到一定分数时增加health/life。在附加到 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) 这样的模数的问题是它一直 returns truescore == 75 .. 所以它需要额外的 bool flag anyway.

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

并且根本不会在 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;
}