b83*_*962 2 c# 2d unity-game-engine
我正在制作一个无尽的亚军游戏。并希望在达到某个分数时增加健康/生命。在附加到 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我使用以下几行来增加里程碑的健康状况,但必须无休止地复制代码以创建多个里程碑。
if (score == 75 || score == 76 && one == true)
{
scriptInstance.health++;
one = false;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在不重复代码的情况下每增加 75 点生命值?
modulo like 的问题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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
一个缺点可能是你知道你必须healthCounter = 0在你重置的任何地方重置score = 0......但你也必须对任何标志解决方案做同样的事情;)