Making an array that contains object with one of 2 tags

Hi.
I’m trying to make an array that contains GameObjects with the tag “RedTeam” or “BlueTeam”
I have this code here to make the array

GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag)

and I was hoping to make it something like this:

GameObject[] go = GameObject.FindGameObjectsWithTag(targetTag || targetTag2)

But as you probably have guessed, that didn’t work either…

If you know a solution to this, please write one :wink:

Thanks for reading
-Frank

2 Answers

2

Using Generic Lists and System.Linq works quite well.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Example : MonoBehaviour 
{
	string[] tags;
	List<GameObject> gameObjects = new List<GameObject>();

	void Start()
	{
		tags = new string[]{"targetTag", "targetTag1"};
		foreach(GameObject go in GameObject.FindObjectsOfType (typeof(GameObject)))
		{
			if(tags.Contains (go.tag))
				gameObjects.Add (go);
		}
		print (gameObjects.Count);
	}
}

And if I'll be calling this function every 10th second or so with 50+ enemies, will it cause loss of performance?

Not if you're calling every 10 seconds. I just wouldn't call it in Update().

Ok. Won't call it in the Update() ;) Thanks for the help ;)

If this solution works out for you, don't forget to tick the answer / vote up ;) Happy Developing

This works quite well - I know you wrote this as an example - but as an improvement, I would let the user fill in the tags array from the inspector instead of newing it up in Start.

Clunk’s answer works pretty nice - but just for pure convenience - you could use Linq here as well:

GameObject[] gos = FindObjectsOfType(typeof(GameObject))
                   .Cast<GameObject>()
                   .Where(g => g.tag == "Bartle" || g.tag == "Doo")
                   .ToArray();

(FindObjectsOfType returns a Object[] hence the Cast())

You could wrap that in a static function:

public static GameObject[] FindObjectsWithTags(IEnumerable<string> tags)
{
	return Object.FindObjectsOfType(typeof(GameObject))
			.Cast<GameObject>()
			.Where(go => tags.Contains(go.tag)).ToArray();
}

Usage:

string[] tags = new[] { "Bartle", "Doo", "BlackCops", "FlatLine" };
GameObject[] gos = FindGameObjectsWithTags(tags);

The function takes an IEnumerable - so you could pass it a regular array, a list, an arraylist, etc.