- Home /
Missiles don't go for random targets...
Hi gang I made a simple missile lock on and wanted the missiles to search for a random game object... but they all go for the one game object when i have multiple GameObjects of "TeamOne" or "TeamTwo"
public bool TeamOne;
public bool TeamTwo;
public GameObject Target;
public float MissileSpeed = 60;
// Use this for initialization
void Update () {
if (TeamOne == true && Target == null) {
Target = GameObject.FindGameObjectWithTag ("TeamTwo");
}
if (TeamTwo == true && Target == null) {
Target = GameObject.FindGameObjectWithTag ("TeamOne");
}
transform.Translate(Vector3.forward * MissileSpeed * Time.deltaTime);
transform.LookAt (Target.transform);
}
}
Answer by Bunny83 · Sep 17, 2017 at 11:16 AM
Uhm GameObject.FindGameObjectWithTag
finds the first object with the given tag. Why should it return a random object?
You may want to use GameObject.FindGameObjectsWithTag
(note the additional "s") which returns an array of all objects with that tag. Then you can use Random.Range to pick a random object from that array.
if (TeamOne == true && Target == null) {
var objs = GameObject.FindGameObjectsWithTag ("TeamTwo");
if (objs != null && objs.Length > 0)
Target = objs[Random.Range(0, objs.Length)];
}
if (TeamTwo == true && Target == null) {
var objs = GameObject.FindGameObjectsWithTag ("TeamOne");
if (objs != null && objs.Length > 0)
Target = objs[Random.Range(0, objs.Length)];
}
Your answer
Follow this Question
Related Questions
"GameObject.Find();" not working 2 Answers
Better solution for GameObject.FindGameObjectsWithTag 2 Answers
random limitation memory game 0 Answers
Find Define GameObject Problem. 2 Answers
Lightning with random intervals 2 Answers