using UnityEngine;
using System.Collections;
public static class MehtodExtension
//定义一个方法拓展的静态类
{
//拓展方法的语法,用 this GameObject obj 就是为了在gamobject.中出现这个方法 固定于法
public static T GetOrAddCompont<T>(this GameObject obj, string path = "") where T : Component
//定义一个静态方法,返回泛型的值,传入泛型的值,并且用where来限制这个泛型的类型
{
Transform t;
//定义一个transform 定义这个transform就是为了获得脚本挂在的物体,或者路径查找后找到的物体,赋值给transform
if (string.IsNullOrEmpty(path))
//如果传入的路径为空
{
t = obj.transform;
//transform就为这个物体的transform(相当于t成为了传参里的物体)
}
else
{
t = obj.transform.Find(path);
//如果路径不为空,则就为find到的路径???(这个路径是查找场景中的物体的,可以用来找到子物体加"/")
}
//上面的只是为了单纯的拿到需要添加组件的物体!!!!
if (t == null)
//如果transform为空则debug(这时候的t其实是一个物体,transform)
{
Debug.LogError(">>>>>>GetOrAddCompont is not found at path:" + path);
return null;
}
T res = t.GetComponent<T>();
//定义一个泛型的变量,并获取泛型的组件(当这个物体是有的,然后就查找使用GetOrAddCompont<T>输入的类型T,例如imag等)
if (res == null)
//如果res没有找到定义的T的组件,说明res身上没有挂载这个T类型的组件,就给他添加组件,
上面的那一句和这一句两个的功能就是:这个物体身上有T类型的组件就直接获取,没有就添加
{
res = t.gameObject.AddComponent<T>();
//则给这个res添加组件(T)
}
return res;
// 然后返回这个组件,是为了得到: Image a = GetOrAddCompont<ima>;
}
public static string ABCD(this GameObject obj)
//给gameobject.出来方法的标准公式
{
return "aaaa";
}
}