- Home /
When Enemy looses health all enemies die
Hey everyone. So the point of this current script is that it moves to the left(toward the castle), but checks to see if enemies are active and to kill them before going to the castle. He moves, he sees all the enemies and can attack them, however when he does attack them they all take the damage and die.
They all share the same health script so I can only imagine that is the problem, but I wanted to check before spending an hour in the wrong area.
Code:
var MoveSpeed : int = 5;
var Castle : Transform;
static var AlliesDetected : boolean = false;
function Update ()
{
var Allies : GameObject[] = GameObject.FindGameObjectsWithTag("Ally");
var ClosestAlly: GameObject;
var ClosestAllyDistance = Mathf.Infinity;
for(Ally in Allies)
{
var dist = (transform.position - Ally.transform.position).sqrMagnitude;
if(dist < ClosestAllyDistance)
{
ClosestAllyDistance = dist;
ClosestAlly = Ally;
}
}
if(ClosestAllyDistance < 1)
{
Debug.Log("InRange!!!!");
AlliesDetected = true;
Attack();
}
else
{
AlliesDetected = false;
}
if(AlliesDetected == false)
{
var DistanceToCastle = Vector2.Distance (transform.position, Castle.transform.position);
if(DistanceToCastle < 1)
{
//Debug.Log("In range!");
}
else
{
transform.Translate(Vector3.left * MoveSpeed * Time.deltaTime);
}
}
}
function Attack()
{
AllyAi.HP --;
}
Thanks for any and all help!
Only way that "AllyAi.HP" should work is either if you declare it is a component at the top (you haven't shown your variables) or if the HP variable/property of the class AllyAi is static, which would be wrong. Let us know which of the two is the case
Oh I didn't even realize I skipped the Variables up there, I'll fix that in a moment... AllyAI.HP is a static since that was what the console was yelling at me for. Saying that it had to be static.
$$anonymous$$aking a static variable makes it global. And therefore there is only one reference of that particular variable. That's the reason all your AIs have the same amount of hp. What you need is to acces other scripts. This may be a good read for you http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html
It does work, but is there a way to access multiple without having to create 500+ references?
Actually, I noticed that when the NPC dies, the script for reference dissapears, so I can just have it deter$$anonymous$$e which gameobject I want to reference after.
You could read this one: http://unitygems.com/script-interaction1/
Your answer
Follow this Question
Related Questions
Problem with substracting life to multiple gameObjects (c#) 2 Answers
enemy attack not recognizing players stats 1 Answer
How To Make Player Health Increase if in a Certain Animation State 1 Answer
Pulling multiple objects 0 Answers
Destroy Enemies With Tag/Color/Name according a indicator. 0 Answers