c# - 达到分数后如何增加健康
问题描述
我正在制作一个无尽的跑步游戏。并希望在达到一定分数时增加健康/生命。在附加到 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)
一直返回,所以无论如何它都需要一个额外的标志。true
score == 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;
}
}
}
一个缺点可能是知道你必须重置healthCounter = 0
你重置的任何地方score = 0
......但你也必须对任何标志解决方案做同样的事情;)
推荐阅读
- android - 在实时数据库 Firebase 中处理同时更新时出现问题
- html - 为地址标签创建可打印的 HTML 页面
- html - jQuery Mobile 上的关闭按钮关闭整个页面
- excel - 将变量导出到 Excel
- scala - Scala Akka Typed - 使用 ask 在行为内部发送请求
- python - 在python中将month_year值转换为月份名称和年份列
- flutter - 在 Flutter PageViewModel 中移除标题周围的光环
- firebase - Flutter 从 firebase 获取特定数据
- excel - 宏将行移动到另一个工作表但忽略新工作表中的公式
- pandas - 熊猫似乎两次合并相同的数据框