/// <summary>/// 通过路径找到指定类型的组件/// </summary>/// <param name="path">path: 指定要查找的组件所在的GameObject的路径</param>/// <param name="parent">parent: 指定查找的GameObject的父对象,默认为null,表示在整个场景中查找</param>/// <typeparam name="T">指定类型的组件</typeparam>/// <returns>返回找到的指定类型的组件,如果未找到,则返回null</returns>public static T FindComponent<T>(string path, GameObject parent = null) where T : Component{// 如果没有指定父对象,则在整个场景中查找GameObject go = parent != null ? parent.transform.Find(path).gameObject : GameObject.Find(path);if (go != null){return go.GetComponent<T>();}return null;}
默认的写法:
nameField = GameObject.Find("nameField/Placeholder").GetComponent<Text>();
调用该泛型方法时:
nameField = FindComponent<Text>("nameField/Placeholder");
genderField = FindComponent<Text>("genderField/Placeholder");