- Home /
Find Many GameObjects by name
Hello!I want to find many GameObjects with name "something+LOD1".How i can do it?GameObject.Find return only one GameObject but i need many!!Thanks
Answer by paulaceccon · Apr 05, 2013 at 06:58 PM
foreach(GameObject gameObj in GameObject.FindObjectsOfType<GameObject>())
{
if(gameObj.name == "something+LOD1")
{
//Do what you want...
}
}
Thanks, but I don't need to search "something".I mean,how I can write code that unity will find all game objects which name contains "lod1" and some other words?
if(gameObj.name.Contains("+LOD")) // ... add to a list or do something with it right away
That's all it takes. This answer is basically right, just the .Contains
portion refines it to what you just asked.
The point is that Unity doesn't provide a built-in way of doing what you're asking for. there isn't a multiple-gameobjects version of Find() (by name) like there is with tags.
So you have to get a list of all the GameObjects, and then go through checking their names using the usual string methods.
That's what pauleccon's solution does, and Dracorat's amendment makes it check for inclusion of a string rather than equality.
To extend that further so as to "check for 'lod1' and some other words", you could just put "&&" inbetween multiple calls to gameObj.name.Contains(). If you want a more sophisticated check then regex pattern-matching might be useful.
Answer by Gurc · Apr 05, 2013 at 06:55 PM
Give them a common tag, and use GameObject.FindGameObjectsWithTag(objectsTag); I hope you know how to create tags.