Gaming in Unity

12. Unity 2D Game 8 - Damage Zone


A Damage Zone will reduce the health of SpriteCharacter!

Step 1 - Adding Damage Zone

First, import DamageZone.png into Assets -> Environment.

Add DamageZone to the Hierarchy.

Add a Box Collider 2D to the DamageZone GameObject and enable Is Trigger.


We now need to write a script to make the area reduce health.

Create a new script called DamageZone in Assets -> Scripts.

This will look more or less the same as the HealthCollectible script with three key differences:

This line will ensure the zone continuously applies the damage over time:

void onTriggerEnter2D will be changed to onTriggerStay2D.

This will make health be reduced and not increased by the zone:

controller.changeHealth(1) will now be controller.changeHealth(-1).

Also remove Destroy(gameObject) so the damage zone doesn't disappear after collision.


Attach the DamageZone script to the DamageZone object in the Hierarchy.

Press play and move SpriteCharacter into the DamageZone and notice health almost immediately decrease to 0. SpriteCharacter also won't take damage if standing still.

To fix damage while standing still, select SpriteCharacter and change Sleeping Mode to Never Sleep in the Rigidbody 2D component.


Step 2 - Adding Invincibility to SpriteController

Now, to stop health immediately decreasing to 0, we need to add to SpriteController script.

Open SpriteController script.

Add three new variables:

public float timeInvincible = 2.0f;
bool isInvincible;
float invincibleTimer;


Add an if statement to void Update(). This counts down the time that SpriteCharacter remains invincible.


Add a few lines of code to ChangeHealth to check whether SpriteCharacter is invincible.


SpriteCharacter should now only get damaged every two seconds of staying in the damage area!

Created by: David Corish