Reputation: 43
So all I want to do is to increase my score by one when an object is destroyed. The objects are destroying but my score is not increasing... Heres my code:
public Transform obstacle;
public GameObject Obstacle;
public Text Score;
public int counter;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (obstacle.transform.position.z <= - 3)
{
Destroy(Obstacle);
counter = counter + 1;
}
Score.text = counter.ToString();
}
Any help is appreciated.
Upvotes: 0
Views: 527
Reputation: 41
I'm going to assume you put this script on the obstacle. The obstacle will be unable to add to the score because it and the script on it were just destroyed. You could add the score before destroying it or you could use the OnDestroy method to add to the score. If this isn't the case then @Kjnold's answer should work.
Upvotes: 1
Reputation: 124
First, make sure you initialize counter you cant add to a variable that is empty. So in Start() set counter = 0. then instead of counter = counter + 1; you can do counter++; https://docs.unity3d.com/2018.3/Documentation/ScriptReference/UI.Text-text.html this will have some usful examples.
Upvotes: 1