结论:
-
所有的寻找对象的函数原则上都不应该出现在Update/FixedUpdate这些频繁调用的函数里
-
这些函数往往在Start Awake OnEnable等这些初始化或者事件函数里使用。
Transform.Find (高效,可路径、可隐藏、)
GameObject.Find (低效) GameObject.FindWithTag (少用) GameObject.FindGameObjectsWithTag (少用) Resources.FindObjectsOfTypeAll (低效,少用)
Object.FindObjectsOfType (Type type) (低效,少用)
GetComponentsInChildren( true)(低效,少用)
https://forum.unity.com/threads/gameobject-find-vs-gameobject-getcomponent.249741/
1.通过对象名称 (1).transform.Find (string name)
通过名字查找子对象并返回它,找不到返回null
- 注意如果参数中只有对象名称那么仅能查找所有儿子中的对象看是否有相同名称的,而不能查找再后面的后代。
- 但是如果参数中包含 ‘/’ 字符,将像路径一样穿越层次去查找相应名称的物体。 eg:
Transform aFinger = transform.Find("LeftShoulder/Arm/Hand/Finger");
- 然而很多情况下我们不知道对象层级(比如模型过于复杂或者想灵活控制),我们可以用递归的方式去查找:
private Transform FindChildInTransform(Transform parent,string child)
{
Transform childTF = parent.Find(child);
if(childTF != null)
{
return childTF;
}
for(int i=0;i
关注
打赏