- Home /
searching through hierarchy
can someone point me in the direction how to search game objects by keyword or partial name i know about GameObject.Find, FindWithTag and GameObject.FindGameObjectsWithTag but that works if you know the exact name or tag, what if i know the name partially? how to handle this?
Answer by Ben 14 · Mar 07, 2011 at 04:42 PM
I second VS48's answer as being the cleanest, but if you're not worried about perfs you can do something simpler like this:
[WARNING - BAAAAD PERFS]
GameObject FindByPartialName(string searchString)
{
foreach (Object obj in Object.FindObjectsOfType(typeof(GameObject)))
{
if (obj.name.Contains(searchString))
return obj as GameObject;
}
return null;
}
Answer by Mystyr Nile · Nov 12, 2010 at 05:52 PM
At the upper-right corner of the hierarchy pane, next to "Create", you should see a text input box with a magnifying glass and "All" in it. Type into that box to search all of your assets already existent within the scene.
hmmm i wasnt really clear i guess, i want to be able to search the objects run time, with partial name of the object in the scene
i am not asking about the assets
Answer by VS48 · Nov 12, 2010 at 08:22 PM
Unless you have a compelling reason for doing partial name/tag matching, I'm going to say it's a bad idea and you should almost certainly search for another way to accomplish that goal. For example, maintain a static dictionary of lists to each type of object you may want to find. For example,
using System.Collections.Generic;
public class HorribleObjectList : MonoBehaviour { public enum MyObjectTypes { Clown=1, Tree, Missile, Etc };
public static Dictionary<MyObjectTypes, List<GameObject>> AllTypesOfObjects;
public static void YoRegisterMyObjectFool(GameObject newObject, MyObjectTypes objectType)
{
if(AllTypesOfObjects == null)
AllTypesOfObjects = new Dictionary<MyObjectTypes, List<GameObject>>();
if (!AllTypesOfObjects.ContainsKey(objectType))
{
AllTypesOfObjects.Add(objectType, new List<GameObject>());
}
AllTypesOfObjects[objectType].Add(newObject);
}
}
Then from your Clown controller you can be like,
void Start()
{
HorribleObjectList.YoRegisterMyObjectFool(gameObject, HorribleObjectList.MyObjectTypes.Clown);
}
Or something. Anyway, now HorribleObjectList.AllTypesOfObjects[HorribleObjectList.MyObjectTypes.Clown] will have all your clowns, and HorribleObjectList.AllTypesOfObjects[HorribleObjectList.MyObjectTypes.Missile] is a list of all the missiles, etc.
Hope this helps...
Your answer
Follow this Question
Related Questions
Search function in Hierarchy 1 Answer
Finding objects with TextMeshPro component. 1 Answer
Where and how are gameobjects stored in files? 0 Answers
Locate asset in hierarchy 1 Answer
Hierarchy search "NOT" modifier? 1 Answer