Reference all objects in an Array except for the object the script is on.
I have a list of hostile objects that I want to avoid each other when they get a specific distance away from each other, so I take all the objects, and when they are 20 (units) away they will rotate slightly to avoid collision.
hostileShips = GameObject.FindGameObjectsWithTag("Hostile");
for (int i = 0; i < hostileShips.Length; i++)
{
if (Vector3.Distance(transform.position, hostileShips[i].transform.position) < 20)
{
transform.rotation = Quaternion.Slerp(transform.rotation, transform.rotation * Quaternion.Euler(0, .05f, 0), 3f);
}
}
I just want to do this for all objects in the list except for the object that this script is on, as the object this script is on has the Hostile tag. So it counts itself, and since its distance is constantly 0 it just turns infinitely. I just want to omit the gameobject the script is on from this for loop.
Answer by tormentoarmagedoom · Jun 19, 2018 at 10:02 AM
Good day.
You need then to check if hostileShips[i] is the object containing the script, and skip the current iteration of the "for sentence". The variable gameObject (not capital G like GameObject) means the object containing this script. So insert this line right before cheking the distance.
So just insert this line before cheking the distance
if ( hostileShips[i] == gameObject)
{
continue;
}
Continue will make the for to skip the current iteration and comence with the nextone.