- Home /
Help with GameObject.FindGameObjectsWithTag
So I am trying to find all the enemies in the game when the missile is shot. The problem I'm having is that GameObject.FindGameObjectsWithTag is returning an array of length zero instead of giving me an array of all the enemies. I've checked to make sure that I do in fact have enemies in the game with the "Enemy" tag on them. Heres my code for it. Im hoping it just something small or I forgot to click something but any help would be greatly appreciated!
public float bulletSpeed;
public float rotSpeed;
public GameObject[] potentialTargets;
public float maxRange;
public float maxAngle;
GameObject lockedTarget;
void Start(){
if (potentialTargets == null) {
potentialTargets = GameObject.FindGameObjectsWithTag("Enemy");
}
Debug.Log(potentialTargets);
if(potentialTargets.Length == 0) {
Debug.Log("Length is zero");
}
foreach (GameObject target in potentialTargets) {
float dist = Vector2.Distance(transform.position, target.transform.position);
float angle = Vector2.Angle(transform.position, target.transform.position);
Debug.Log(dist);
Debug.Log(angle);
if(dist < maxRange && angle < maxAngle) {
lockedTarget = target;
}
}
}`
Start()
is executed during the object initialization, when it's enabled. do the enemy objects exist at that point?
Yes. This script is attached to the missile and runs whenever the missile is instantiated (shot) at which point the enemies are already existing in the game
Answer by Owen-Reynolds · Apr 07, 2015 at 08:50 PM
Potential targets is a public
. In Unity, those are never null (they always have some size set in the Inspector. Even if it's zero, before Awake() Unity new
s the array.)
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
FindGameObjectsWithTag is not workin... 1 Answer
Save Script and use it causes Errors 0 Answers
Tagged objects not returning value 0 Answers
Multiple Cars not working 1 Answer