Yet another damage question

Before I start, yes, I am new to Unity, and yes, I have looked at the FPS tutorial for help, as well as used google…

Im having some trouble with damage. When the player walks into a trigger (located in front of the enemy), they should lose 10 Health/2sec. My problem is that the player is not taking damage.

Here is the enemy damage script:

var damage : int = 10;
var DamageRate : int = 2;
private var enable : boolean = true;

function OnTriggerStay(col : Collider) {
    if(col.gameObject.tag == "Player" && enable == true){
    	enable = false;
        col.gameObject.BroadcastMessage("ApplyPDamage", damage);
        yield WaitForSeconds(DamageRate);
        enable = true;
    }
}

And the player health script:

var health : int = 100;
var Player : Transform;
var Spawn : Transform;
var labelPos : Rect = Rect(20,10,300,50);
var Skin : GUISkin;

function Start () {
	OnGUI ();
	ApplyPDamage ();
}

function OnGUI () {
  	GUI.skin = Skin;
  	GUI.Label(labelPos, "Health: " + health + " / 100");
}

function ApplyPDamage () {
	var damage : int;
    health -= damage;

    if(health <= 0) {
        Die();
    }
}

function Die () {
   Player.position = Spawn.position;
}

Any help?

Thanks is advance, Geko_X

1 Answer

1

Well there are a few problems I can see straight up- first of all, your ApplyPDamage function does not take any paramaters! For this function to work, it should be structured like

function ApplyPDamage(damage : int) {
    health -= damage;
    if(health <= 0)
    {
        Die();
    }
}

The second problem is that, if you do this, your player will take a huge amount of damage because the trigger will not disable itself! The issue is that you can’t use yield WaitForSeconds outside of a Coroutine. Instead, you should create a second function which can be started as a coroutine, and which re-enables the damage trigger when it finishes.

function WaitThenEnable(time : float) {
    yield WaitForSeconds (time);
    enable = true;
}

Which should be called using StartCoroutine(WaitThenEnable(time));

I hope this helps!

Thankyou!!! That had been getting to me for ages!!! Thankyou!