- Home /
How do i get my script to work?
i found a script to find the closest enemy and it works fine. but when the enemy is destroyed it doesn't remove the enemy out of the array. can someone help me please? here is the code im using:
var enemies : GameObject[];
function Update() { enemies = GameObject.FindGameObjectsWithTag("enemy");
if(enemies.length > 0) { target = enemies[0]; var dist = Vector3.Distance(transform.position, enemies[0].transform.position);
for(var i=0;i<enemies.length;i++) {
var tempDist = Vector3.Distance(transform.position, enemies[i].transform.position);
if(tempDist < dist) {
target = enemies[i];
}
}
i tried using:
if (enemies[i] == null)
{
enemies.RemoveAt(i);
}
but then it says that it isnt a member of unityengine.GameObject[].
Answer by Casper 1 · Apr 25, 2011 at 10:55 AM
The easiest way would probably to make your array static and then access it through your enemy script.
i tried using if(enemies[i] ==null) { enemies.RemoveAt(i); }
but it said that RemoveAt wasnt a member of UnityEngine.GameObject
You might want to take a look here http://answers.unity3d.com/questions/9788/how-do-you-use-removeat-or-add-with-an-array-of-gameobjects
Answer by VCCGeek · Apr 25, 2011 at 01:04 PM
RemoveAt() isn't part of the array class. If I recall correctly (which I might not), you can swap the element that you want to remove with the first or last element of the array, and then use either shift() or pop() on it. shift() removes and returns the first element of an array, and pop() removes and returns the last.
I would give you some code, but I'm so rusty at JS that I'm afraid my code would probably be non-working.
to do that i need to change the variable to an array but i also need it to be a game object. is there a way to combine them so i can use it as an array and use it as a gameobject.
Your answer
Follow this Question
Related Questions
Pick the oldest object from an array. 2 Answers
Removing objects from an array 2 Answers
Array Element number 1 Answer
What is wrong with this code? 0 Answers
Cycle through targets. 2 Answers