首页 > 解决方案 > 达到分数后如何增加健康

问题描述

我正在制作一个无尽的跑步游戏。并希望在达到一定分数时增加健康/生命。在附加到 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 点生命值?

标签: c#unity3d2d

解决方案


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

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

根本不要重复检查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;
        }
    }
}

一个缺点可能是知道你必须重置healthCounter = 0你重置的任何地方score = 0......但你也必须对任何标志解决方案做同样的事情;)


推荐阅读