I'm currently working on a radar system for my space game, and I am trying to work out how to add gameobjects, by tag, to either a list or array that can then be used in other methods. I can't do this manually because I will be procedurally generating each level with varying amounts of these objects: planets, enemies, asteroids etc. I have looked up at least 5 or so ways of doing this however I have noticed that some methods seem to be deprecated for Unity 5 and no longer work (they were given the thumbs up 3 or 4 years ago), or they just don't work the way I need them to i.e. being local to a method instead of the class. Any help will be greatly appreciated.
-
what have you done so far? Try using listsmaraaaaaaaa– maraaaaaaaa2015-06-15 01:40:58 +00:00Commented Jun 15, 2015 at 1:40
-
I have tried both arrays and lists, however when I try to manually add each GameObject.FindObjectsWithTag etc. to either, I am told that they have no overload for that, and when i try iterating through using a counter this also fails to add any gameobjects to my list/array. Although this did seem to be the closer of the two to actually work: as in no errors other than it couldnt find any objects in my scene.JonHerbert– JonHerbert2015-06-15 02:02:40 +00:00Commented Jun 15, 2015 at 2:02
-
essentially this answers.unity3d.com/questions/729141/… and this answers.unity3d.com/questions/776637/… and a number of other answers via googleJonHerbert– JonHerbert2015-06-15 02:05:05 +00:00Commented Jun 15, 2015 at 2:05
Add a comment
|
1 Answer
public List<GameObject> myListofGameObject = new List<GameObject>();
Start(){
myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName"));
myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName2"));
myListofGameObject.AddRange(GameObject.FindGameObjectsWithTag("TagName3"));
foreach(GameObject gc in myListofGameObject){
Debug.Log(gc.name);
}
}
Works Perfectly fine for me, Make sure to add the System class for linq generics.
3 Comments
JonHerbert
Well, I agree this should work, the code makes perfect sense to me, but i'm getting this: The best overloaded method match for `System.Collections.Generic.List<UnityEngine.GameObject>.Add(UnityEngine.GameObject)' has some invalid arguments when I add even just one gameobject as you have in the code above. I have also added system.collections.generic as well as linq, but it still doesn't work.
JonHerbert
I noticed that if I changed the FindObject to singular rather than plural I can add one of those gameobjects with that tag, but not multiple objects with the same tag. I need to add all Asteroids for example to this list, then all planets etc.
JonHerbert
Aha! It was .AddRange I needed to add multiple gameobjects at once! .Add only allows one at a time. Thanks for the help Aizen!