天天看點

Unity常用函數擴充(一)—— GetOrAddComponent()

功能

實作擷取Transform或者GameObject上的元件,若擷取不到則自動添加該元件

代碼實作

public static T GetOrAddComponent<T>(this Transform origin) where T : Component
    {
        T component = origin.GetComponent<T>();
        if (component == null)
        {
            component= origin.gameObject.AddComponent<T>();
        }
        return component;
    }
    
    public static T GetOrAddComponent<T>(this GameObject origin) where T : Component
    {
        T component = origin.GetComponent<T>();
        if (component == null)
        {
            component = origin.AddComponent<T>();
        }
        return component;
    }
           

使用示例

var gameMgr = transform.GetOrAddComponent<GameManager>();
var gameMgr = gameObject.GetOrAddComponent<GameManager>();