简体   繁体   English

用关键字Unity查找GameObjects

[英]Find GameObjects with keyword Unity

How can I find GameObjects with a keyword in Unity ? 如何在Unity中找到带有关键字的GameObjects?

Actually, I have a lot of GameObject named like that : 实际上,我有很多这样命名的GameObject:

  • Concrete Floor [289483] 混凝土地板[289483]
  • Concrete Floor [289487] 混凝土地板[289487]
  • Wall part [293291] 墙体部分[293291]
  • Part [321043] 部分[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(在[]括号内),因为它是GameObject名称的相关部分。

ID should be unique, but I'm not sure it is ! ID应该是唯一的,但我不确定它是!

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. 据我了解, GameObject.Find(name)只搜索对象的确切名称。

Thanks for your help ! 谢谢你的帮助 !

I think you're referring to something like a GameObject's tag? 我认为您指的是类似GameObject的标签?

http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html 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. 它仍然使用直接字符串,但不是GameObject的名称,因此管理起来更简单。 You can assign tags to GameObjects and most commonly via Prefab. 您可以将标签分配给GameObjects,最常见的是通过Prefab。

http://answers.unity3d.com/questions/54040/can-i-get-a-tags-element-number.html 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. 这表明要将Unity3d标记转换为int / enum类型,则必须自己进行管理。 But that should be fairly simple using a Dictionary or something. 但是使用Dictionary或类似工具应该很简单。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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