- Home /
GameObject.FindGameObjectsWithTag() to find Prefabs which are not in the scene
Hi, I'm trying to get an array of all prefabs with a certain tag. GameObject.FindGameObjectsWithTag() however only lists instances of prefabs within the scene. Is there any way to generate an array which includes all prefabs, whether they are currently in the scene or not?
I know I could create an array and then drag every object into it in the editor, but I would prefer if there was an automated solution.
What I'm trying to do is create a dictionary so that I can instantiate any object with Items[itemName], where itemName is a string.
static public Dictionary<string, GameObject> Items = new Dictionary<string, GameObject>();
void Start () {
GameObject[] itemList = GameObject.FindGameObjectsWithTag("Item");
foreach(GameObject item in itemList) {
Items.Add(item.name, item);
}
}
Answer by whydoidoit · Jun 25, 2012 at 11:58 AM
You need to use this:
Resources.FindObjectsOfTypeAll(...
Which will get any objects included in the project for the active scenes in the build and also anything in the Resources folders.
Excellent, never heard of this before. Thank you. Is there anyway to define a custom 'type'? Or how would I include only objects with a certain tag?
Yep:
using System.Linq;
var taggedObjects = Resources.FindObjectsOfTypeAll(typeof(GameObject)).Cast<GameObject>().Where(g=>g.tag=="YOURTAGHERE").ToList();
That seems to work exactly like I hope it would; thanks again.