Simplifying Bricks

I had a cool idea if anyone wants to try it. I found that making so many brick prefabs was cumbersome, so I came up with another solution if anyone wants to play with it. I have only one brick prefab with the publicly exposed max hits on it. My prefab has just a standard white color selected in the editor. I created a function to set the color based on the amount of maxHits the block as:

void SetColor(){
	switch (MaxHits - TimesHit)
	{
	case 5:
		this.GetComponent<SpriteRenderer>().color = Color.magenta;
		break;
	case 4:
		this.GetComponent<SpriteRenderer>().color = Color.cyan;
		break;
	case 3:
		this.GetComponent<SpriteRenderer>().color = Color.red;
		break;
	case 2:
		this.GetComponent<SpriteRenderer>().color = Color.green;
		break;
	case 1:
		this.GetComponent<SpriteRenderer>().color = Color.yellow;
		break;
	default:
		break;
	}
}

Now that you have the function, you can call it in the Awake Function.
void Awake(){
SetColor ();
}

Lastly , every time your brick is hit, call SetColor:

void OnCollisionEnter2D(Collision2D other){
	if (other.gameObject.name == "Ball") {
		TimesHit++;
		SetColor ();
	}
}

Once you do that, layout your bricks any way you want, and each time you hit one, it changes to the color of the next amount of max hits. FUN!

3 Likes

Privacy & Terms