简体   繁体   中英

Find GameObjects with keyword Unity

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 !

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM