JS script for applying damage to player when within a certain proximity to the Enemy.

Hello there. I’m very new to unity and am just now getting into scripting specifically Javascript. Right now I’m trying to come up with a script for an enemy to apply damage to the player when the player is within a certain distance to the enemy.Kinda in the same vain of Slender the arrival where the closer you get to slender man the more damage he does to you. I know the best way to do it is to have the enemy send a message to the player and call on the payer script, I just don’t know how I would write that. Can anyone point me in the right direction, of where I can learn to do that?

I would start out creating a big sphere collider around the enemy and setting it as a trigger. Then whenever the player gets inside it’s proximity zone the player script detects that it’s in the collider and takes damage.

player script:
public static var intrigger : bool = false;

if(intrigger == true){
takedamage();
}

enemy script:

function OnTriggerEnter (other : Collider) {
player.intrigger = true;
}

Might be wrong as I don’t use javascript.

Ya, I really easy way to do this is to have a Sphere collider that is attached to the enemy. Scale it to the size you need and make sure that the isTrigger is checked on the collider in the editor.

Then attach a script to the enemy that includes the function, OnTriggerEnter ( Unity - Scripting API: Collider.OnTriggerEnter(Collider) ), in it and you may want to use OnTriggerStay and OnTriggerExit accordingly as well.

It would look something like this on the enemy side:

 function OnTriggerEnter (other : Collider)
            {
       if( other.gameObject.tag == Player )
       {
        other.gameObject.GetComponent(HealthScript).DamageCaused();
        }
    	}
    
    function OnTriggerStay (other : Collider)
            {
    	  if( other.gameObject.tag == Player )
       {
        other.gameObject.GetComponent(HealthScript).DamageCaused();
        }
    	}

In the example above, it expects you to set the Player tag in the editor to “Player”

And like this on the player side:

var health : float = 100;
var damage : float = 5;

function DamageCaused()
            {

             health = health - damage;

            if( health <= 0 )
            {

            Die();
        }
        }

I haven’t tested this and I rarely use JS, but something like this should work.