2
votes

I want to make a Breakout game in Unity. I made a lot of the functions work except the "count" function. I want the "count"function to tell the user how many bricks are left. Every time a brick (gameObject) gets destroyed, the int variable "bricks" will decrease by one. The problem I have is that it only updates once (from 104 to 103) then stops updating. Here is my script:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class Spawner : MonoBehaviour {

public int bricks = 104;
public Text triggerText;

void Start(){
    triggerText.text = "Bricks: "+bricks;
    }

public void OnCollisionEnter(){

    DestroyBrick ();

}

public void DestroyBrick(){
    bricks--;
    Destroy (gameObject);
    triggerText.text = "Bricks: "+bricks;
    }

edit: I forgot to mention that I added this script to my Brick gameObjects (104 of them) in order for them to break when collided.

3

3 Answers

3
votes

I think you have one spawner instance in your scene. When DestroyBrick is called you kill this instance by calling Destroy (gameObject);. So you stick at 103.

Possible solutions:

  • Remove the call to Destroy if it's one spawner for your 104 bricks
  • If it is rather a brick component attached to each spawned Brick instance, either
    • delegate counting to another object let's say BrickCounter
    • make member variable bricks static

EDIT (inspired by @BradleyDotNET's comment):
Static member is OK for testing. But I would always prefer creating a separate class which is responsible for holding the brick count.

1
votes

Since each instance of the brick game objects has a unique instance of this behavior, you get this:

  1. Brick 1 starts with count 104
  2. Brick 2 starts with count 104
  3. Brick 1 is destroyed, its count goes to 103
  4. The text is set to 103 by Brick 1
  5. Brick 2 is destroyed, its count goes to 103
  6. The text is set to 103 by Brick 2

Giving the appearance that the count only decrements once. To fix this, you need a global script (assigned to a single gameObject) that manages the count. When a brick is destroyed, its behavior should find (or be passed) this behavior instance and invoke a method on it:

public void BrickDestroyed()
{
    bricks--;
    triggerText.text = "Bricks: "+bricks;
}
1
votes

If this block of code is on each of your 104 game objects, then every time this occurs, an integer named 'bricks' is created with a value of 104.

Declare this variable somewhere publicly accessible outside of all of these objects, and only decrement and update text on the brick objects.