[SOLVED] brickCount not counting down correctly

Greetings!
While playing around with level creation I noticed that when the ball breaks a yellow brick the brickCount variable drops by one twice. Thus, as the level progresses, the variable fails to keep track of the actual number of bricks. For example in this screenshot

scrshot1

scrshot2

You can see that although one brick was broken, the number of bricks is 20 instead of 21.

Here’s the relevant code of the Brick.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Brick : MonoBehaviour {

    public Sprite[] hitSprites;
    public static int brickCount = 0;
    public AudioClip crack;
    public GameObject smoke;
    


    private int timesHit;
	private LevelManager levelManager;
    private bool isBreakable;



    // Use this for initialization
    void Start () {
		timesHit = 0;
		levelManager = GameObject.FindObjectOfType<LevelManager> ();
        isBreakable = (gameObject.tag == "Breakable");

        if (isBreakable)
        {
            GameObject[] initialBricks = GameObject.FindGameObjectsWithTag("Breakable");
            brickCount = initialBricks.Length;            
        }
        Debug.Log("Brick Num: " + brickCount);
    }
	
	private void OnCollisionEnter2D(Collision2D collision){
        //We bind the sound clip with the point where the ball is not the brick itself!
        AudioSource.PlayClipAtPoint(crack, transform.position,0.8f);
        if (isBreakable)
        {
            HandleHits();           
        }
	}

    void HandleHits()
    {
        timesHit++;
        int maxHits = hitSprites.Length + 1;
        if (timesHit >= maxHits)
        {
            brickCount--;
            levelManager.BrickDestroyed();

            //Create the smoke object at the brick;s position
            Instantiate(smoke, gameObject.transform.position, Quaternion.identity);

            Destroy(gameObject);
            Debug.Log("Brick Num: " + brickCount);

        }
        else
        {
            LoadSprites();
        }
    }

    void LoadSprites()
    {
        int spriteIndex = timesHit - 1;
        if (hitSprites[spriteIndex])
        {
            gameObject.GetComponent<SpriteRenderer>().sprite = hitSprites[spriteIndex];
        } else
        {
            Debug.LogError("Brick sprite missing");
        }
    }
}

My only deviation from the tutorial, by the way, is the way the number of bricks is being calculated inside the Start() method, so I believe this is where the bug could hides. Yet, I 'm unable to see the where lies the faulty logic.

Thank you in advance!
Harry.

Hi Harry,

I couldn’t find a reason why this code would decrement the brick count by two, so I copied and pasted it in my project and it works fine. So at least you can be confident the problem isn’t coming from your Brick script. Since your hierarchy shows two smoke instances and two audio sources being created, it looks like the OnCollisionEnter2D() message gets sent twice, but I don’t know why that would be. Sorry I can’t be more helpful than that.

1 Like

If that is the case then it may be worth checking the Ball script as well as the Block script - perhaps the same functionality has been added to both - as they are the only two objects making contact.

If you are still having problems Harry, zip up the project and pop a link to it here, you will probably have to share it via Dropbox or Google Drive etc (the forum only allows 10mb uploads) and I will happily have a look for you.

Thank you for your prompt answers! Sebastian, you are right… After digging into step by step debugging in VS for the first time, I noticed that each collision counts for two. But the reason why eludes me :frowning: I’m familiarizing myself with that tool these days.

I’ll keep searching though.

Rob, I’d be glad if you lent me your expertise here… I expected the debugging of such a simple program to be relatively easy. Here’s the link:

Thank you for your time, gentlemen :slight_smile:
Harry.

2 Likes

Hi Harry,

You have two BoxCollider2D components on the yellow bricks. Each one receives a collision. Thus, your code is actually doing what it should. What isn’t right is the duplicated BoxCollider2D on each brick.

Note - your yellow brick prefab doesn’t have the second BoxCollider2D, so you can select each of the yellow bricks in the scene, and, one by one, click on the Revert button to put them back as per the prefab.

Once done, the displayed count reports correctly (read: as desired).


On an unrelated note - have you noticed that if you move your paddle back and forth quickly the ball kinda rolls a bit to the side in either direction?

You can resolve this by changing the script execution order. Edit -> Project Settings -> Script Execution Order

  • within the Inspector, click on the + icon at the bottom of the list
  • select the Ball
  • drag the ball to beneath Paddle
  • click Apply

image


Hope this helps :slight_smile:

1 Like

Oh my, I was looking at the code and missed the obvious :S When we changed the paddle, I accidentally messed with the prefabs so I guess that’s when it happened. Thank you for the insight! Much appreciated!
H.

1 Like

You’re more than welcome.

I checked the scripts first myself, just via a text editor (I try to save some time not launching Unity if I don’t need to!), as my initial thought was that perhaps there was some duplicate functionality on both the brick and the ball, as those were the only two obvious items involved. As I looked at the code I saw mention of the LevelManager, so took a quick look at that too… these all seemed good.

So launching Unity was the next step and then I checked the specific brick you indicated in your screenshot and noticed the second BoxCollider2D in the Inspector. Check all of the others, all of those were the same. Checked the green bricks, yep, only one BoxCollider2D on those. Checked the yellow brick prefab, only one on that. I assumed you had probably tried/tested something out and perhaps forgotten to put it back as it was.

No biggy, it happens to us all and sometimes you kinda become blind to seeing things when you’ve been looking at them yourself for so long.

Please post a link to your uploaded game when you’ve completed this section so we can have a play and enjoy it :slight_smile: