Sunday, 29 November 2015

Damage in Unity

Damage is critically important to a variety of games, and can be applied to many different situations using C# in Unity depending on the player's need. Some games have the player get hurt by bumping into an enemy, others have them get injured when falling from a high enough place. I will explain how someone can implement code that causes damage below:

Damage usually works hand in hand with collision detection, as when the two hitboxes collide it triggers the code to activate. Having your health as a numerical value which can rise and deplete in-game is as simple as creating a public float variable. Here's an example of code used to store health in a player, and a copy of it is placed inside every instance of an enemy (as posted by (ankit.tiks007, 2015) from Unity answers): "
  1. public static float health = 100;
  2. void OnCollisionEnter(Collision col){
  3. if(col.gameObject.name == "Player"){
  4. health-=5;
  5. }
"
Essentially all the code listed above does is when an enemy, which contains said code, collides with the player character, it reduces 5 from their maximum pool of 100 health. Using the health value, various tasks could then be coded in more depth, such as destroying the character when the health reaches 0, knocking them back upon the collision to show force, or creating a duplicate of the enemy code I listed that's designed to be inside healing items instead, where it raises the player's health by 5 instead of reducing it to add another layer of skill to the game.

No comments:

Post a Comment