How to implement a working score?

I’m making an Arkanoid game and I have this simple code to increment a score variable when my ball collides with the bricks. However when i print out the variable in doesnt seem to change. Can someone help me, im still a beginner.

    int score;

void Start(){
	score = 0;
}

// Simply delete the bricks that the ball collides with
void OnCollisionEnter2D(Collision2D coll){

	if (coll.gameObject.name == "Ball") {
		score++;
		Debug.Log (score);
		Destroy(gameObject); //Destroys the brick
	}
}

It looks like you have this attached to each individual brick. In that case each brick will be increasing and printing its own version of score.

You have a couple options to fix

  • Make score static. As long as the game is single player this should work.
  • Move score onto a single manager class. Consider the singleton pattern for this
  • Move this script onto the ball, thus maintaining a single instance of score

Do some reading up on OOP. Seems you haven’t quite grasped the concept of instances yet.

Note: I’m only guessing you have this attached to the brick. I could be completely wrong here.