面板拖拽

这种方式简单高效,但是不适合用于大型项目,一方面容易遗漏导致比较难解决的bug,另一方面使得我们的项目不具有可迁移性,不利于团队协作。


代码获取

Find

(1) GameObject.Find()

参数是string类型的物体名称,返回值是gameobject

(2) Transform.Find()

参数是string类型的物体名称,返回值是transform

缺陷是无法找到未激活的物体,并且查找的时候需要遍历,效率比较低。


FindWithTag

GameObject.FindWithTag

这种方式效率比较高,但是需要提前设置好标签。


GetChild

Transform.GetChild()

参数是整数类型,意味着其下面组件的顺序编号,从0开始。这种方式的缺陷是如果项目中物体的位置被改变了,就会出现错误。


以下为代码示例:

    //我要获取的组件在脚本所在的组件的子物体的子物体上  
//以下是三种实现方式:
inputFieldAccount = this.transform.GetChild(0).GetChild(0).GetComponent<InputField>();
inputFieldAccount = this.transform.Find("InputFieldAccount").GetComponent<InputField>();
inputFieldAccount = GameObject.Find("InputFieldAccount").GetComponent<InputField>();


References

Transform.Find:

​https://docs.unity3d.com/ScriptReference/Transform.Find.html​

GameObject.Find:

​https://docs.unity3d.com/ScriptReference/GameObject.Find.html​

GameObject.FindWithTag:

​https://docs.unity3d.com/ScriptReference/GameObject.FindWithTag.html​