Q: Attacking/killing enemies?

Hey, I’ve just started learning unity and came across a huge problem that doesn’t seem to advanced to fix, I just don’t know how!

Im currently working on a 2d platform game and the movement/attacking is done, the only problem is that when i attack an enemy and it gets below 0 health all enemys with the same script attached to them dies aswell.

This is what I use right now, both scripts are attached to the enemy as i couldn’t figure out a way to put them on my player and still make it work.Do i need to change my attacksystem or is it a way to simply fix it?

(Sidenote, i only gain exp equal to one kill even if i kill more than one with the same script attached)

var attackable : boolean = false;
var enemyhealth : float = 200;
var attackcooldown : boolean = false;
var attackspeed : float = 0.5;
function Attack () {
enemyhealth -= 50;
	yield WaitForSeconds(attackspeed);
		attackcooldown = false;
		}
function Update (){
if(Input.GetKeyDown("1")  (attackcooldown == false)){
Attack();
attackcooldown = true;
}

To bring it to a point - in the moment you have enemies all with a script attached which says:
If you press a key make me suffer.
So you have no real target you are fighting. You just hit them all.
You have to know which enemy you are fighting.

I get your point, iam now trying to set the enemy as my target when they are in my attackrange.
For some reason it doesn’t work, iam not sure that this is a “legit” piece of code. (im not sure if the unity engine understands my script).
The error it gives me says: __NullReferenceException: Object reference not set to an instance of an object__¨

This is what im trying to do

Attached to the enemy:

function OnCollisionEnter(theCollision : Collision){
if(theCollision.tag == "attackrange"){
playerscript.target ==this.gameObject;
}
}

Attached to the player:

function Attack () {
target.health -= 50;
	yield WaitForSeconds(attackspeed);
		attackcooldown = false;
		}

How is the variable playerscript initialized on the enemy object? It seems that unless you set the value of playerscript prior to what you’ve posted playerscript won’t contain a valid reference to the player.

You likely want to do:

playerscript = theCollision.gameObject.GetComponent(playerscript);
playerscript.target = gameObject;