英文:
Can't add score in Unity
问题
I'm trying to add +1000 to a score when my player hit an item (I'm trying to do an endless runner game).
I have in my game manager the following code:
private float currentScore = 0;
void Update(){
if(!isGameEnded){
currentScore = Time.timeSinceLevelLoad * 10f;
if(scoreBonus){
currentScore += 1000;
scoreText.SetText(currentScore.ToString("0"));
scoreBonus = false;
}
scoreText.SetText(currentScore.ToString("0"));
}
}
And I have an itemCollision script in which I update my GameManager's scoreBonus variable:
void OnCollisionEnter(Collision collisionInfo){
if(collisionInfo.collider.tag == "Player"){
FindObjectOfType<PlayerCollision>().ActivateInvicibility(invisibilityDuration);
FindObjectOfType<GameManager>().scoreBonus = true;
Destroy(gameObject);
}
}
The thing is when I hit the item, the score updates really fast, I can see the +1000 happened and then it disappears. I've tried to log the score, but everything seems normal. When it hits an item, its value changes in the log but not in my score text.
英文:
I'm trying to add +1000 to a score when my player hit an item (I'm trying to do an endless runner game).
I have in my game manager the following code:
private float currentScore = 0;
void Update(){
if(!isGameEnded){
currentScore = Time.timeSinceLevelLoad * 10f;
if(scoreBonus){
currentScore += 1000;
scoreText.SetText(currentScore.ToString("0"));
scoreBonus = false;
}
scoreText.SetText(currentScore.ToString("0"));
}
}
And I have an itemCollision script in which I update my GameManager's scoreBonus variable:
void OnCollisionEnter(Collision collisionInfo){
if(collisionInfo.collider.tag == "Player"){
FindObjectOfType<PlayerCollision>().ActivateInvicibility(invisibilityDuration);
FindObjectOfType<GameManager>().scoreBonus = true;
Destroy(gameObject);
}
}
The thing is when I hit the item, the score update really fast, I can see the +1000 happened and then it disappear. I've tried to log the score but everything seems normal, when he hits an items, its value changes in the log but not in my score text.
答案1
得分: 2
这个问题是这一行:
currentScore = Time.timeSinceLevelLoad * 10f;
这将覆盖对当前分数所做的任何更改,因为分数是计算的结果。
为了保持简单,您可以创建另一个变量来存储额外的得分点,然后在显示时将它们相加。
private float currentScore;
private float bonusScore;
..
if (scoreBonus)
{
bonusScore += 1000;
}
scoreText.SetText((currentScore + bonusScore).ToString("0"));
英文:
This issue is this line here
currentScore = Time.timeSinceLevelLoad * 10f;
This overrides any change you make to current score, since the score is the result of a calculation.
To keep things easy, you can make another variable to store additional score points, then add the two together when displaying.
private float currentScore;
private float bonusScore;
..
if (scoreBonus)
{
bonusScore += 1000;
}
scoreText.SetText((currentScore + bonusScore).ToString("0"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论