- Home /
After I initially add score it keeps adding.
Once I destroy a game object that is supposed to add 5 points to my score it continuously adds points. How do I fix this?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Code : MonoBehaviour {
public int score;
public Text scoreText;
public GameObject enemy;
public bool enemyDead;
// Use this for initialization
void Start () {
score = 0;
}
// Update is called once per frame
void Update () {
if(enemy == null)
{
enemyDead = true;
}
if(enemyDead == true)
{
score += 5;
}
DisplayScore();
}
public void DisplayScore()
{
scoreText.text = "Score: " + score;
}
Answer by JincSoft · Mar 20, 2016 at 04:25 PM
The fix that @Tymewiz provided gets rid of one score adding loop problem. The current thing that I see causing an issue is that unless you are assigning the enemy gameobject in the inspector it will always have the default value of null.
@Tymewiz fix:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Code : MonoBehaviour {
public int score;
public Text scoreText;
public GameObject enemy;
public bool enemyDead;
private bool enemyKilledFlag;
// Use this for initialization
void Start () {
score = 0;
}
// Update is called once per frame
void Update () {
if(enemy == null)
{
enemyDead = true;
enemyKilledFlag = true;
}
if(enemyDead && enemyKilledFlag)
{
score += 5;
enemyKilledFlag = false;
}
DisplayScore();
}
public void DisplayScore()
{
scoreText.text = "Score: " + score;
}
Answer by Tymewiz · Mar 18, 2016 at 01:09 PM
once the score incrementation has been done the first time we need to flag that the code has been executed before
bool enemykilledflag = true;
if(enemyDead == true && enemykilledflag)
{
score += 5;
enemykilledflag = false;
}
Can you implement that into my code because I am still having issues. Once I add your fix it just doesn't count at all.
Your answer
Follow this Question
Related Questions
Point system, something wrong 1 Answer
Is it possible to add a point to the score, everytime the Player rotates 180°? 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How can I make my score editable? 1 Answer