- Home /
C# adding lives to player by collision
I have a script in C# for player lives, when collision with bullet is detected, player loses 1 live. I would like to add a collision with object tagged "medKit", and then player would get 100 or whatever more lives.
using UnityEngine; using System.Collections;
public class NewPlayerLives : MonoBehaviour { //Fields public int lives = 50; public Texture2D h4; public Texture2D h3; public Texture2D h2; public Texture2D h1; public Texture2D h0;
void OnGUI() { if(lives > 40){ GUI.Label (new Rect (900,25,100,100),h4); } else if(lives > 30){ GUI.Label (new Rect (900,25,100,100),h3); } else if(lives > 20){ GUI.Label (new Rect (900,25,100,100),h2); } else if(lives > 10){ GUI.Label (new Rect (900,25,100,100),h1); } else if(lives > 0){ GUI.Label (new Rect (900,25,100,100),h0); }
}
//Trigger Function
void OnTriggerEnter(Collider col){
if (col.tag == "bullet")
{
Debug.Log("Collision with bullet detected");
//Decrease Life and destroy bullet
lives -= 1;
Destroy(col.gameObject);
}
else if(col.tag=="medKit")
{
lives +=100;
}
//Check if we destroy our enemy
if (DidEnemyDie())
Application.LoadLevel(2);
//Destroy(gameObject);
}
//Function return true if life < 0
bool DidEnemyDie()
{
return lives <= 0 ? true : false;
}
}
Unfortunately it's not working, probably this is not the right way to do it. Maybe any of you can tell me what am I doing wrong...
Thanks.
Answer by Statement · Mar 11, 2011 at 04:20 PM
- Make sure your medKit has a collider.
- Make sure your medKit collider is a trigger.
- Make sure your medKit collider has a proper layermask.
- Make sure your medKit really have the 'medKit' tag.
thanks, forgot to check "Is trigger" function and was looking for problem somewhere else... :D
Your answer
![](https://koobas.hobune.stream/wayback/20220613112347im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Array value not changing? 1 Answer
Adding new animation? 1 Answer
How to add/Build a game for Xbox 360? 2 Answers
How can I make a playlist last the whole gameplay? 1 Answer
how to add position delta of moving object to the player 0 Answers