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;
}
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;
}
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;
}