making enemy kill player when enemy close enough.

Hi, I’m trying to make the enemy take health off the player when the enemy is close enough.
I tried using OnCollision, but the bullets the player shot at the enemy counted as collision, so when I shot the enemy the level would reload.
I was trying to attach the first script to the enemy, and the player health script to the player.

I’m not great at coding at all and I’m sure I’m missing something simple. If anyone could please give me some feebdback, it would be awesome.

The enemy “attack” on player.

#pragma strict
var TheDammage = 50;
var player : GameObject;
var enemy : GameObject;


function Start () {
player = GameObject.Find("player");
enemy = GameObject.Find("enemy");
}

function Update () {
if ("enemy" < 2 "player");
function ApplyDamage();
}
#pragma strict

var Health = 100;

function ApplyDamage (TheDamage :int)
{
Health -= TheDamage;

if(Health <= 0)
{
Dead();
}
}

function Dead()
{
//Destroy (gameObject);
Application.LoadLevel ("Mockron_Level3");
}

Some notes/tips:

  • Try to stay consistent with your formatting. In the first script, your function definition opening bracket is on the same line as the parameter list. In the second, you have it on the following line. Neither is “wrong” per se, but pick one and stick with it.
  • I’m not sure what lines 13 and 14 in the first script are supposed to be doing, but they’re not doing anything. I’m actually kind of surprised 13 doesn’t throw an error. Check out the proper formatting for if statements and function usage below:
// Proper if statement format
if (condition1 == condition2) {
  // Do something
}

// Function declaration
function myFunction(optionalParameter) {
  // Do stuff
}

// Call defined function
myFunction();
  • I’m guessing that mess on lines 13/14 is actually triggering your ApplyDamage method to run repeatedly until the player dies. There’s a number of ways to fix this, but the best one I can think of would be to start over. Follow a few more tutorials and get more comfortable with the language syntax, then try again.
1 Like