Hi guys, I have this health script I created for my player, can any one show me how I could integrate damage and death when the player comes close to an enemy? This is the only thing not working in my game and I have a project completion deadline of the 3rd May, so any kind of detailed help would be gratefully appreciated. Thanks in advance!
var maxHealth : int = 100;
var HealthGUI : GUIStyle;
var rect1: float;
var rect2: float;
var rect3: float;
var rect4: float;
function Update () {
if( maxHealth < 0){
maxHealth = 0;
}
if( maxHealth > 100){
maxHealth = 100;
}
}
function OnGUI (){
GUI.Label(new Rect(Screen.width/rect1,Screen.height/rect2, Screen.width/rect3,Screen.height/rect4 ),""+maxHealth+"%",HealthGUI);
}
You can add a Sphere collider to an enemy object, let’s say 5 units large. Set the collider to istrigger. When your player (which should also have a collider, usually a capsule collider) touches the sphere collider, the OnTriggerEnter Event is called.
From here you can call a function on your player object such as:
function takesDamage(amount){
maxHealth -= amount;
}
Then when you check if(maxHealth<0)
you know your player has died. Here you can add effects but ultimately you want to call Destroy(player)
. Unity - Scripting API: Object.Destroy
I prefer using OnCollisionEnter
for detecting hits for combat since it’s very precise (at a performance cost). If you’re not so concerned about accuracy, LyanApps’s advise to use triggers would certainly do the trick.
However, to your question, after a collision is detected (via either method described), you need to alert the hit object that a collision occurred.
I use something similar to this:
void OnCollisionEnter(Collision collision) {
ContactPoint contact = collision.contacts[0];
GameObject other = contact.otherCollider.gameObject;
float someRandomDamageValue = 20.5f;
other.SendMessage("OnHit", someRandomDamageValue ,SendMessageOptions.DontRequireReceiver);
}
Your player (or anything that needs to get hit) can have a component (I call mine ‘HealthController’) attached, that is in charge of health and has the “OnHit” function. That function then is called on the object that was hit! Here’s an example of the HealthController:
public class HealthController : MonoBehaviour {
public float HP;
public float MaxHP;
public void OnHit(float damage) {
HP -= damage;
HP = Mathf.Clamp(HP, 0f, MaxHP);
if(HP == 0) {
BeginDeathSequence();
}
}
private void BeginDeathSequence() {
// Oh Noes! We Died!
}
}
Works really nicely, and it’s a clean way to communicate the collision and damage.