More than one enemy?

I have a wolf, when I damage that wolf, it’s health ticks down by 20, when I kill that wolf, the wolf despawns – it works.

However, if i spawn a second wolf, then I kill the first wolf, the second wolf will crash my game, because the instance of the health object no longer exists.

How do I resolve this?

Thanks.

Hello,

Let me see if Understand correctly:

You have Wolf1 with HPobject and Wolf2 with HPobject, once you kill Wolf1, and error comes up and the game crashes that the Wolf2 object has no HPobject because the object no longer exists?

If I recall correctly I had a similar issue when I assigned in inspector the object (HPobject) to a variable using a prefab. The solution is to reference the HPobject from code.

So for example, put the HPobject as a child of the Wolf1 and same for Wolf2 then use something like:

GameObject child = transform.GetChild[0];

then do whatever to the variable child.

Hope that helps.

Hi @JohnnyMccrum, you probably reduce health on prefab or just in in script which cause problem because you decrease health on global variavle, ie:

// in Wolf script
public static float wolfHealth;
if(wolfHealth <= 0)
//kill
// in player script
Wolf.wolfHealth -= 10;

That will decrease health for all wolfs, and if it’s 0 it’s killing wolf, if you instantiate wolf with 0 health and it will kill inmidiately so here is problem. Use something like that:

// in Enemy script
public float health;

public void TakeDamage(float damage)
{
health = health - damage;
if(health <= 0)
// kill
}

// in Sword script
public float swordDamage;

void OnCollisionEnter(Collision col)
{
if(col.tag == "Enemy")
col.gameObject.GetComponent<Enemy>().TakeDamage(swordDamage);
}
//you may check first if gameObjcet have got script "Enemy" but if tag is Enemy so let's say it will have that script