Find Game Objects "Containing" string.

Hi Unity Community.

Thank you for taking the time to look at this question.

Context:
Lets say I have 10 objects imported from a 3rd party software. For the sake of argument, we are going to say its 100 balls. In the 3D application they are all named Ball, but when imported into unity they are named Ball 01, Ball 02 …

Now usually, I would select them all and tag them so that I can just find objects with tag via script but in this case they are deep in hierarchies and difficult to select them all.

Actual Question:
Can I use a gameObject.Find(“Ball”) type function that would look for all objects whos name Contains the string name?

Thank you.

You could use a recursive function to find in some object and all of its children the objects whose name starts with “Ball” - like this:

function Start(){
    NameContains("Ball", transform);
}

    static function NameContains(start: String, transf: Transform) {
        if (transf.name.StartsWith(start)){
            // this object starts with the string passed in "start":
            // do whatever you want with it...
            print(transf.name); // like printing its name
        }
        // now search in its children, grandchildren etc.
        for (var child in transf){
            NameContains(start, child);
        }
    }

If the objects are childed to independent objects, create an empty object (remember to reset its position and rotation), attach the script above and child all objects to it.

You could write an editor script to do the dirty job before runtime. It could look like this:

public string objectName = "Ball";
public string tag = "Ball";

@ContextMenu("Rename")
void Rename()
{
    GameObject[] gos = (GameObject[])FindObjectsOfType(typeof(GameObject));
    for(int i=0;i<gos.Length;i++)
        if(gos*.name.Contains(objectName))*

gos*.tag = tag;*

}
We’re finding all GameObject whose name contains objectName and set their tag , so its easy to work with them at runtime. You could also fill an array with them or whatnot.

Add this extension to your project:

public static IEnumerable<Transform> Children(this Transform t)
{
    foreach(Transform c in t)
        yield return c;
}

Now you can do fancy things with LINQ like this:

transform.Children().Where(x=>x.name.Contains("Patrol"))

Or make another fancy extension specifically looking for a string contained in the name. Extensions for the win!