How to find the Transform for all the Gameobjects in a list.

Im trying to write a foreach statement to find the transform for all the gameobjects in a list so i can get the x y onscreen location for each. i can white them all out 1 at a time like

Vector3 a = camera.WorldToScreenPoint(Targets[0].position);
		float aX = a.x;
		float aY = a.y;

but in each lvl of my game there is a different number of game objects. Any suggestions would be greatly appreciated.

2 Answers

2

If you want to do this only with the objects that have a certain tag, get them in an array at Start with FindGameObjectsWithTag:

private GameObject[] targets;

void Start(){
  targets = GameObject.FindGameObjectsWithTag("target");
}

// iterate through the items with a foreach:

  foreach (GameObject target in targets){
    Vector3 a = camera.WorldToScreenPoint(target.transform.position);
    float aX = a.x;
    float aY = a.y;
    ...
  }

Notice that the foreach loop gets the current element in the variable target, thus you don’t need to (and actually can’t) know which’s its index.

Thank you Aldo Naletto!! the wording was eluding me but that is exactly what i needed to know. To answer the why asked by ZoomDomain i'm using a point at targeting system that basically when the target is in the middle of the screen you select it as the target. knowing the onscreen x y of each game object lets me call wether or not the target is in the middle of the screen. Thank you both for your responses =]

you need to explain what you’re doing with all the transform positions, because normally you wouldn’t just find the positions, you would use the positions each for something, and you would include that in the loop to find them all.

in unity we mostly loop through the values in an array/list like this-

for (var i=0;i<targets.Length;i++){

var aX= targets*.transform.position.x*

var ay= targets*.transform.position.y*
}
and
for (target in targets){
var aX= target*.transform.position.x*
var ay= target*.transform.position.y*
}
At the end of the day you can access each element of the array at the same time as you use them for a calculation, rather than just converting them to a variable.