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);
}
}
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)];
}