c# - 分数达到时如何增加健康

标签 c# unity3d 2d

我正在制作一款无尽的跑酷游戏。并希望在达到一定分数时增加健康/生命。在附加到 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) 这样的模数的问题是它总是返回 truescore == 75 .. 所以无论如何它都需要一个额外的 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 ... 但您必须执行相同的操作也可以使用任何标志解决方案;)

关于c# - 分数达到时如何增加健康,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172099/

相关文章:

c# - 来自浏览器的 WCF 方法调用返回 400 错误请求

c# - 为什么 C# 允许在 case 之后而不是之前的语句?

c# - 处理对象之间的交互

ios - 退化的顶点和 GL_LINE_STRIP

algorithm - 二维网格可达目的地

c# - 我无法向 WCF 服务发送超过 13 Mb 的数据(超出最大请求长度)

c# - WebResponse.GetResponseStream() 可以返回空值吗?

c# - 如何在负索引处启动数组 C#(UNITY)

c# - 统一 AdMob - ClassNotFound : com. google.unity.ads.UnityAdListener

opengl - 使用 OpenGL 的快速调色板屏幕 blit