- Home /
Grabbing GameObjects and putting into Transform array?
Hi there!
So, I was wondering on how to make something grab GameObjects and putting them into a array.
I've tried this
public Transform[] Waypoints = GameObject.FindGameObjectsWithTag("Waypoint");
But It doesn't work.
If anyone could help me that would be great! Thank you!
Answer by Jeff-Kesselman · Apr 29, 2014 at 04:34 PM
FindGameObject returns an array of gameObject, not their transforms., See https://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html
Your error message should have made this clear, always look at your compiler messages first, and the online docs next.
What you need to do is loop on them and get their transforms.
eg
public GameObject[] WaypointObjects = GameObject.FindGameObjectsWithTag("Waypoint");
public Transform[] WaypointTransforms = new Transform[WaypointObjects.Length];
for(int i=0;i<WaypointObjects.Length;i++){
WaypointTransforms[i] = WaypointObjects[i].transform;
}
Thank you so much!! I really appreciate this! I have a question though!
Will it grab duplicates of a same GameObject or will it only grab it once?
EDIT: Im very confused on how to set this up? ^^" Still kinda new to c#... Ive done AI and stuff, but this is the first time to actually do Waypoints and things
If you're wanting to add/remove waypoints on the fly it might be better to use a list ins$$anonymous$$d of an array as they can be re-sized dynamically.
I prefer Array, because it's a lot easier... Sorry about that!
Your answer
![](https://koobas.hobune.stream/wayback/20220613143851im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Make NPC travel to waypoint 1 Answer
Lists, Arrays and c# equivilent of js Array() 1 Answer
Conceptual Question on Creating Arrays at Runtime 1 Answer
Distribute terrain in zones 3 Answers