unity通过路径找到特定对象并获取指定类型组件的泛型方法

		/// <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");

相关推荐

  1. SpringAPI获取实际类型

    2024-05-14 18:18:07       72 阅读
  2. 如何获取T真实类型

    2024-05-14 18:18:07       60 阅读
  3. json类型转换对象含有

    2024-05-14 18:18:07       50 阅读
  4. c#设置或者获取一个整数指定bit

    2024-05-14 18:18:07       34 阅读
  5. 对于学习

    2024-05-14 18:18:07       35 阅读
  6. 之广泛类型

    2024-05-14 18:18:07       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-14 18:18:07       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-14 18:18:07       97 阅读
  3. 在Django里面运行非项目文件

    2024-05-14 18:18:07       78 阅读
  4. Python语言-面向对象

    2024-05-14 18:18:07       88 阅读

热门阅读

  1. 单链表与双链表

    2024-05-14 18:18:07       24 阅读
  2. 蓝桥杯单片机组——国赛1 各模块的基础模板

    2024-05-14 18:18:07       29 阅读
  3. 微信小程序-禁止页面下拉回弹

    2024-05-14 18:18:07       31 阅读
  4. Frida逆向与利用自动化

    2024-05-14 18:18:07       33 阅读
  5. NIUKE SQL:大厂面试真题(四) 【某滴打车】

    2024-05-14 18:18:07       30 阅读
  6. 回溯算法(Backtracking Algorithm)

    2024-05-14 18:18:07       28 阅读
  7. react生命周期及用法

    2024-05-14 18:18:07       23 阅读
  8. 【贪心算法】【Python实现】最优装载问题

    2024-05-14 18:18:07       28 阅读