There are different ways you would go about this depending on your particular circumstances.
Ultimately, you can not search for all active game objects based off both type and name, at the same time. You can easily search for all active game objects based off type, and search the resulting list for all game objects of type that use name. You also want to consider whether searching for game objects by tag would be more appropriate for your requirements.
Below, I have provided two methods for searching for game objects by type and name. One can be easily used on the fly, the other is provided as a standalone method, and can be used more dynamically.
Find all GameObject(s) by type and name
To complete the search, simply search for objects based off type, and search through the resulting list for objects that match the name.
using UnityEngine;
using System.Collections.Generic;
...
TypeToLookFor[] firstList = GameObject.FindObjectsOfType<TypeToLookFor>();
List<Object> finalList = new List<Object>();
string nameToLookFor = "name of game object";
for(var i = 0; i < firstList.Length; i++)
{
if(firstList[i].gameObject.name == nameToLookFor)
{
finalList.Add(firstList[i]);
}
}
Note that you ask to "find objects", and I interpret that to literally mean you wish to have a resulting Object
array. Any type you can look for, in this way, will be compatible with Object
.
You could also retain the type you originally search for, in this way. In the above example, we could change List<Object> finalList
to List<TypeToLookFor>
with no problems. We could also use List<GameObject> finalList
, and find the actual gameObject
reference with finalList.Add(basicAIList[i].gameObject
, if we wanted a list of game objects.
Consider that you may want to search like this multiple times. It might be more useful to have a standalone method that can perform the required search, and take in custom types and names.
...
public List<Object> FindObjectsOfTypeAndName<T>(string name) where T : MonoBehaviour
{
MonoBehaviour[] firstList = GameObject.FindObjectsOfType<T>();
List<Object> finalList = new List<Object>();
for(var i = 0; i < firstList.Length; i++)
{
if(firstList[i].name == name)
{
finalList.Add(firstList[i]);
}
}
return finalList;
}
We can then call this method as FindObjectsOfTypeAndName<TypeToLookFor>("name to look for")
.
I assume that we will always be looking for types that inherit from MonoBehaviour
, but this will usually be the case, with custom types. If you need to change this, ensure that you also change the type of MonoBehaviour[] firstList
.
FindObjectsOfType
(with Objects pluralised) returns an array of all such objects found. You can then iterate over the array to find one with a matching name. But please don't. ;) – DMGregory Nov 3 '16 at 19:22