- Home /
How to cause damage on collision?
I want it so that when my character walks into a certain object he loses health. Right now when he walks into the object the debug log says hit player, but no health is taken away. Need help fast please. This is the script.
#pragma strict
public var damage = 10;
public var health = 100;
var healthnow;
function Start () {
}
function Update () {
}
function OnCollisionEnter (cool : Collider) {
if (cool.gameObject.name == "AttackThreshhold") {
health = health - damage;
Debug.Log("Hit player");
}
if (health < 0) {
Application.LoadLevel("Close");
}
}
function OnGUI () {
if (GUI.Button (Rect (10,10,150,100), "Your Health is " + health)) {
}
}
your code seems to be alright... aren´t you accessing health variable from other scripts?
$$anonymous$$ake sure that the value of damage in the Inspector for this object is set to 10 (not 0 perhaps).
ok so damage is set at 10, but i get this error that says Script error: OnCollisionEnter This message parameter has to be of type: Collision The message will be ignored.
Answer by jonnyhopper · Oct 27, 2013 at 02:44 PM
Yep so like your message says, OnCollisionEnter has to have an argument of type Collision: http://docs.unity3d.com/Documentation/ScriptReference/Collider.OnCollisionEnter.html
That collision contains the collider object you need
Ok, so the error is gone but no health is being taken away from the player. Sorry im just very new to program$$anonymous$$g and all this.
public var damage = 10;
public var health = 100;
function OnGUI () {
if (GUI.Button (Rect (10,10,150,100), "Your Health is " + health)) {
}
}
function OnCollisionEnter () {
if (gameObject.name == "Enemy") {
death();
Debug.Log("Hit player");
}
if (health < 0) {
Application.LoadLevel("Close");
}
}
function death () {
health = (health - damage);
}