- Home /
Get transform component from all gameobjects with tag
What I am trying to do is that all gameObjects with the tag of "Waypoint" are added to an array of transforms. The only problem is that I can't seem to be able to add them to the transform array as I am not able to access their transform component and assign it per object to the transform array.
private var wayPoints : Transform[];
wayPoints = GameObject.FindGameObjectsWithTag("Waypoint");
//Add the transform component of each object to the wayPoints transform array
var wayPointsArray = new Array(wayPoints);
for(var point : Transform in wayPointsArray){
//Do pathfinding stuff
}
Answer by whydoidoit · Nov 23, 2012 at 10:03 PM
Try this:
import System.Linq;
Then get your components like this:
var wayPointTransforms = GameObject.FindGameObjectsWithTag("Waypoint").Select(function (go) {return go.transform;}).ToArray();
Had been looking for an answer all day - Just saved me alot of frustration. Thanks.
Cool stuff Linq - can do a lot of cool things with lists/arrays :)
Answer by Zacharias3690 · Nov 23, 2012 at 09:58 PM
wayPoints itself is an array of the gameobjects, so why assign a new array for it? just use wayPoints = GameObject.FindGameObjectsWithTag("Waypoint");
for(var i = 0; i < wayPoints.length; i++)
{
//do pathfinding stuff with point = wayPoints[i]
}
I require the Transform component so I can access the position of each point.
for(var point : Transform in wayPointsArray){}
Usualy I would have to add all points in the inspector but I am looking for a more efficient and automated way by just letting unity look for all objects that are taged as waypoints and them adding them to the array.
Your answer
Follow this Question
Related Questions
Transport unknown amout of objects with GameObject array 0 Answers
View an array of the transform position/rotation of all game objects with a specified tag., 0 Answers
Spawning GameObjects with help of classes --- Attaching classes to GameObjects 1 Answer
New Object Pooling Problem 1 Answer
How to set to game objects's position from 2 different game objects arrays equal to each other? 0 Answers