ShoarmaKarma ShoarmaKarma - 1 month ago 34
C# Question

C# Score Counter {Unity3D}

I need to make a score counter for my game.
It partly works, whenever the cube reaches (x)11 the score goes up, and the block will be reset to it's beginning position at (x)12.
The problem is, is that whenever the cube reaches (x)11 it will keep counting +1 until (x)12, when it gets reset the score is around 36 most of the time.
It keeps doing this and I have no clue what I have done wrong, full on noobie here.
Here is my code:

void Start () {
beginPositie = new Vector3 (-4, 0, 0);
transform.position = beginPositie;
score = 0;
}


void Update () {
snelheid = Random.Range (2, 5);
transform.Translate (snelheid * Time.deltaTime, 0, 0);
if(gameObject.transform.position.x>= 12){
transform.position = beginPositie;
}

}

void OnGUI() {
if (gameObject.transform.position.x == 11) {
score = score + 1;
}
GUI.skin = textSkin;
GUI.Label (new Rect (10, 10, 300, 100), "Score: " + score);

}

Answer

This is causing the problem:

if (gameObject.transform.position.x == 11)

Do not compare floats with = because it is never guaranteed that the value of gameObject.transform.position.x will exactly be 11.

That should b changed to:

if (gameObject.transform.position.x >= 11)

Another unrelated problem is OnGUI(). Don't use it. Use the new Unity UI.