Simplified health system?

Hello,

I did my heath and destroy detection a bit different. To me it seems more simple, but I wanted to ask if there is anything wrong with this method.

I created a variable called index. (The index position in the Sprite Sheet array).
I set this variable to -1 on start of the Brick instance.

On collision Exit 2D I have the following code.

	GetComponent<AudioSource>().Play();
	mHealth -= 1;
	if (mHealth <= 0)
	{
		Destroy(gameObject);
		levelM.deleteBrick();    // LevelM is the levelManager. I believe I handled this a bit different too.
	}
	else
	{
		++index;
		this.GetComponent<SpriteRenderer>().sprite = brickSheet[index];
	}

With this method, the index is increased, but as long as the brick doesnt have more hit points than it has images, it will always delete itself instead of increasing index position.

Nice!

I have thought in something similar. I have a block “health” called life and the block is destroyed once life reaches 0. In addition, I added a color changing to the brick so I could easily identify how many lifes the brick has.

Here is how it is:

using UnityEngine;

public class Brick : MonoBehaviour {
public int life;
private LevelManager levelmanager;

void Start () {
    levelmanager = GameObject.FindObjectOfType<LevelManager>();
}
    
void OnCollisionEnter2D(Collision2D collision)
{
    life--;
    if (life == 2)
    {
        GetComponent<SpriteRenderer>().color = new Color(1f,0.30196078f, 0.30196078f);
    }

    if (life == 1)
    {
        GetComponent<SpriteRenderer>().color = new Color(0.388235229f, 0.3372549f, 1f);
    }
    
    if (life <=0)
    {
        Destroy(gameObject);
    }

}

}

Privacy & Terms