0

How can I find GameObjects with a keyword in Unity ?

Actually, I have a lot of GameObject named like that :

  • Concrete Floor [289483]
  • Concrete Floor [289487]
  • Wall part [293291]
  • Part [321043]
  • ...

I already made functions to get the ID of an object (inside the [] brackets) because it is the relevant part of the GameObject name.

ID should be unique, but I'm not sure it is !

Now, I would like to have a function with this prototype :

public static GameObject[] getObjectsWithIdentifier(int identifier)

It would return all of the objects that have the identifier given in parameter. So it's like a search function.

GameObject.Find(name), as I understand it, only make the search for the exact name of the object.

Thanks for your help !

Dean
  • 1,512
  • 13
  • 28

2 Answers2

5

I think you're referring to something like a GameObject's tag?

http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html

This still uses direct strings, but it's not the GameObject's name so it is slightly more managed. You can assign tags to GameObjects and most commonly via Prefab.

http://answers.unity3d.com/questions/54040/can-i-get-a-tags-element-number.html

This demonstrates that to turn a Unity3d tag into an int/enum type then you'd have to manage that yourself. But that should be fairly simple using a Dictionary or something.

Atra Viator
  • 535
  • 2
  • 6
  • It means I should loop through all my objects and assign them in tag theirs ID in the `start()` function, and then I would be able to use `FindGameObjectsWithTags()` ? I can easily have a lot of GameObjects in my scene, so I hoped there would be a better way to do it ! – Dean Apr 23 '15 at 17:15
  • It depends. If you're spawning so many objects I assume you're instantiating them at runtime? You can set a tag on an object via the Inspector at the top left hand side. If you set a tag on a prefab all instantiated objects will have the tag you originally set which is the best practice method. Assigning tags at runtime in my opinion is bad practice. – Atra Viator Apr 23 '15 at 18:04
  • In fact, I'm importing models from .fbx files. Maybe I will have to import FBX at runtime because I can end up to import a lot of them and to make automatic treatment as I import them. But for now, I just import an example fbx by hand inside the inspector – Dean Apr 23 '15 at 18:17
0

Finally, this is the solution I came up with.

This is what I made, of course it iterate, but I think I will create the initial global array only once at the first time you use the function.

public static Object[] findObjectsFromIdentifier(int identifier) {
    Object[] objects = GameObject.FindObjectsOfType( typeof( GameObject ) );
    return objects.Where( obj => getIdentifierFromObject( obj ) == identifier ).ToArray();
}
Dean
  • 1,512
  • 13
  • 28