- Home /
The question is answered, right answer was accepted
Handling multiple tags
My idea is to add multiple gameobjects with different tags and I would like to use List for it, more like using a List as a method. This is what I've had so far.
public void FindObjectsWithTags<GameObject>(string[] tags)
{
var compList = new List<GameObject>();
for (int i = 0; i < tags.Length; i++)
{
var taggedObjects = GameObject.FindGameObjectsWithTag(tags[i]);
compList.AddRange(taggedObjects);
}
}
I've used List many times, but I haven't do List as a method before, plus there's an error on on "var taggedObject = ...." lines, so I'm kinda lost right now. Could someone point me to the right direction? I really want to use this List method because it's the most efficient way to handle multiple tags. Sorry for this idk, lame question maybe? Thanks.
It will help if you paste what error message you got on that line.
It says "Expression denotes a type parameter', where a
variable', value' or
type' was expected" in Unity. While my code editor detects the GameObject as an invalid parameter.
One quick fix to this probably just change var taggedObjects = GameObject.FindGameObjectsWithTag(tags[i]);
to GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tags[i]);
Im sorry, the error still exist even after I changed them.
So the idea is to write multiple tags and get all the gameobjects which have them, clear; thank you miramaslow.
Answer by x4637x · Aug 25, 2017 at 04:10 AM
change public void FindObjectsWithTags<GameObject>(string[] tags)
to public void FindObjectsWithTags(string[] tags)
should fix it.
I have one more question sorry, how do I add the gameObjects to my List above? I'm trying to use this
allTags = new string[]{"Gold", "Emerald"};
allComp = FindObjectsWithTags(allTags);
and error comes out. I've initialized the List<GameObject> allComp = new List<GameObject>();
and string[] allTags;
already. Thanks.
That compList.AddRange(taggedObjects);
is doing what you ask isn't it? All game objects you want to get will be in the "compList" after for loop is done.
All you missing is just return it in the function.
Try this :
public List<GameObject> FindObjectsWithTags(string[] tags)
{
var compList = new List<GameObject>();
for (int i = 0; i < tags.Length; i++)
{
var taggedObjects = GameObject.FindGameObjectsWithTag(tags[i]);
compList.AddRange(taggedObjects);
}
return compList;
}
Follow this Question
Related Questions
How to get variables from a list of a list of gameobjects? 1 Answer
A node in a childnode? 1 Answer
Array of tags, gettings tags using CompareTag 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers