unity3d 常用组件扩展方法

测试使用

using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 测试使用
/// </summary>
public class Test : MonoBehaviour
{
    Button but;
    private Text tex;
    void Awake()
    {
        but = transform.RequireComponent<Button>();
        tex = transform.RequireComponent<Text>();
    }
   
}

unity Component Extention

using UnityEngine;

/// <summary>
/// unity Component Extention
/// </summary>
public static class UnityComponentExtention
{
    /// <summary>
    /// get / add component to target GameObject
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="go"></param>
    /// <returns></returns>
    public static T RequireComponent<T>(this GameObject go) where T : Component
    {
        T comp = go.GetComponent<T>();
        if (comp == null)
        {
            comp = go.AddComponent<T>();
        }
        return comp;
    }
    /// <summary>
    /// get / add component to target Transform
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="trans"></param>
    /// <returns></returns>
    public static T RequireComponent<T>(this Transform trans) where T : Component
    {
        return RequireComponent<T>(trans.gameObject);
    }

    /// <summary>
    /// get / add component to target GameObject, ref tips if is add
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="go"></param>
    /// <param name="isAddNew"></param>
    /// <returns></returns>
    public static T RequireComponent<T>(this GameObject go, ref bool isAddNewComp) where T : Component
    {
        T comp = go.GetComponent<T>();
        if (isAddNewComp = (comp == null))
        {
            comp = go.AddComponent<T>();
        }
        return comp;
    }
    /// <summary>
    /// get / add component to target Transform
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="trans"></param>
    /// <returns></returns>
    public static T RequireComponent<T>(this Transform trans, ref bool isAddNewComp) where T : Component
    {
        return RequireComponent<T>(trans.gameObject, ref isAddNewComp);
    }

    /// <summary>
    /// Get Target Component in Transform layer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="trans"></param>
    /// <param name="layerStr"></param>
    /// <returns></returns>
    public static T FindFirstComponentInChild<T>(this Transform trans, string layerStr) where T : Component
    {
        var tagTrans = trans.FindChild(layerStr);
        if (tagTrans != null)
        {
            return tagTrans.GetComponent<T>();
        }
        return null;
    }
    /// <summary>
    /// Get Target Component in GameObject layer
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="go"></param>
    /// <param name="layerStr"></param>
    /// <returns></returns>
    public static T FindFirstComponentInChild<T>(this GameObject go, string layerStr) where T : Component
    {
        return go.transform.FindFirstComponentInChild<T>(layerStr);
    }
    /// <summary>
    /// Wrapped Func for auto check unreferenced component... suppose is should be deprecated
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="monoBehaviour"></param>
    /// <param name="comp"></param>
    /// <returns></returns>
    public static bool TryFindFirstComponentInChild<T>(this MonoBehaviour monoBehaviour, ref T comp) where T : Component
    {
        if (comp == null)
        {
            comp = monoBehaviour.GetComponentInChildren<T>();
        }
        return comp != null;
    }
    /// <summary>
    /// Wrapped Get Child GameObject
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="layerStr"></param>
    /// <returns></returns>
    public static GameObject FindChildGameObject(this Transform trans, string layerStr)
    {
        var tagTrans = trans.FindChild(layerStr);
        return tagTrans != null ? tagTrans.gameObject : null;
    }
    /// <summary>
    /// Wrapped Set active
    /// </summary>
    /// <param name="go"></param>
    /// <param name="active"></param>
    public static void SetActive(this GameObject go, bool active, bool recursively, bool includeInactive = true)
    {
        go.SetActive(active);
        if (recursively)
        {
            var allTrans = go.GetComponentsInChildren<Transform>(includeInactive);
            for (int i = 0; i < allTrans.Length; i++)
            {
                allTrans[i].gameObject.SetActive(active);
            }
        }
    }

    /// <summary>
    /// Find with type def
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="layerStr"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static Component FindFirstComponentInChild(this Transform trans, string layerStr, System.Type type)
    {
        var tagTrans = trans.FindChild(layerStr);
        if (tagTrans != null)
        {
            return tagTrans.GetComponent(type);
        }
        return null;
    }
    /// <summary>
    ///  Find with type def
    /// </summary>
    /// <param name="go"></param>
    /// <param name="layerStr"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static Component FindFirstComponentInChild(this GameObject go, string layerStr, System.Type type)
    {
        return FindFirstComponentInChild(go.transform, layerStr, type);
    }
    // destroy test
    public static void DestroySelf(this GameObject go, float delay = 0.0f)
    {
        if (!go)
        {
            return;
        }
        if (delay > 0.0f)
        {
            if (Application.isPlaying)
            {
                UnityEngine.Object.Destroy(go, delay);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(go, false);
            }
        }
        else
        {
            DestroyGameObject(ref go);
        }
    }

    public static void SetLayer(this GameObject go, int layer, bool withChildren)
    {
        if (go != null && go.layer != layer)
        {
            go.layer = layer;
            if (withChildren)
            {
                foreach (var tran in go.GetComponentsInChildren<Transform>(true))
                {
                    tran.gameObject.layer = layer;
                }
            }
        }
    }

    /// <summary>
    /// wrapped func for destroy gameobject
    /// </summary>
    /// <param name="go"></param>
    public static void Destroy(UnityEngine.Object obj)
    {
        if (obj != null)
        {
            if (Application.isPlaying)
            {
                UnityEngine.Object.Destroy(obj);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(obj);
            }
        }
    }

    /// <summary>
    /// wrapped func for destroy gameobject
    /// </summary>
    /// <param name="go"></param>
    public static void DestroyGameObject(ref GameObject go)
    {
        if (go != null)
        {
            if (Application.isPlaying)
            {
                UnityEngine.Object.Destroy(go);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(go);
            }
        }
        go = null;
    }
    /// <summary>
    /// wrapped func for destroy gameobject via Transform
    /// </summary>
    /// <param name="go"></param>
    public static void DestroyGameObject<T>(ref T comp) where T : UnityEngine.Component
    {
        if (comp != null)
        {
            var go = comp.gameObject;
            DestroyGameObject(ref go);
        }
        comp = null;
    }
    /// <summary>
    ///  wrapped func for destroy any UnityObject
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="obj"></param>
    public static void DestroyObject<T>(ref T obj) where T : UnityEngine.Object
    {
        if (obj != null)
        {
            if (Application.isPlaying)
            {
                UnityEngine.Object.Destroy(obj);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(obj);
            }
        }
        obj = null;
    }

    /// <summary>
    /// ResetTransform base info
    /// </summary>
    /// <param name="trans"></param>
    public static void ResetTransform(this Transform trans)
    {
        trans.position = Vector3.zero;
        trans.rotation = Quaternion.identity;
        trans.localScale = Vector3.one;
    }

    /// <summary>
    /// ResetTransform base info
    /// </summary>
    /// <param name="go"></param>
    public static void ResetTransform(this GameObject go)
    {
        go.transform.ResetTransform();
    }

    /// <summary>
    /// Temp Copy
    /// </summary>
    /// <param name="trans"></param>
    /// <returns></returns>
    public static Transform CopyTempTransform(this Transform trans)
    {
        var retVal = new GameObject("temp trans").transform;
        retVal.position = trans.position;
        retVal.rotation = trans.rotation;
        return retVal;
    }

    public static void ResetParent(this Transform trans, Transform parent, bool resetTransform = false)
    {
        if (parent != null)
        {
            trans.parent = parent;
            if (resetTransform)
            {
                trans.ResetTransform();
            }
        }
    }

    /// <summary>
    /// Look At 2D Version
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="pos"></param>
    public static void LookAt_2D(this Transform trans, Vector3 pos)
    {
        trans.LookAt(new Vector3(pos.x, trans.position.y, pos.z));
    }
    /// <summary>
    /// Look At Direction
    /// </summary>
    /// <param name="trans"></param>
    /// <param name="pos"></param>
    public static void LookAtDir(this Transform trans, Vector3 dir)
    {
        var pos = trans.position + dir;
        trans.LookAt(pos);
    }

    public static void LookAtDir_2D(this Transform trans, Vector3 dir)
    {
        var pos = trans.position + dir;
        pos.y = trans.position.y;
        trans.LookAt(pos);
    }

    // RectTransform set parent wrapped func, the parent changed will make anchoredposition changed
    public static void WrappedSetParent(this RectTransform rectTrans, Transform parent)
    {
        Vector2 oldPos = rectTrans.anchoredPosition;
        rectTrans.SetParent(parent);
        rectTrans.ResetTransform();
        rectTrans.anchoredPosition = oldPos;
    }

    #region Factory
    // wrapped func to create a new GameObject whitch component attatched
    public static T NewComponent<T>(string objectName = null, Vector3? setPos = null) where T : Component
    {
        var go = new GameObject(objectName ?? ("NewObject_" + typeof(T).Name));
        var comp = go.AddComponent<T>();
        if (setPos.HasValue)
        {
            comp.transform.position = setPos.Value;
        }
        return comp;
    }
    public static string PlayerPrefs_GetString(string key, string defaultString)
    {
        if (PlayerPrefs.HasKey(key) == false)
        {
            PlayerPrefs.SetString(key, defaultString);
            PlayerPrefs.Save();
        }
        return PlayerPrefs.GetString(key);
    }
    public static int PlayerPrefs_GetInt(string key, int defaultInt)
    {
        if (PlayerPrefs.HasKey(key) == false)
        {
            PlayerPrefs.SetInt(key, defaultInt);
            PlayerPrefs.Save();
        }
        return PlayerPrefs.GetInt(key);
    }
    public static float PlayerPrefs_GetFloat(string key, float defaultFloat)
    {
        if (PlayerPrefs.HasKey(key) == false)
        {
            PlayerPrefs.GetFloat(key, defaultFloat);
            PlayerPrefs.Save();
        }
        return PlayerPrefs.GetFloat(key);
    }
    #endregion

    public static AnimationCurve Clear(this AnimationCurve curve)
    {
        int clearCount = curve.length;
        for (int i = clearCount - 1; i >= 0; i--)
        {
            curve.RemoveKey(i);
        }
        return curve;
    }

    public static float GetCurrentClipLength(this Animator animator, float defaultVal = 1.0f)
    {
        var animationClips = animator.GetCurrentAnimatorClipInfo(0);
        if (animationClips != null && animationClips.Length > 0)
        {
            return animationClips[0].clip.length;
        }
        return defaultVal;
    }
    public static float GetNextClipLength(this Animator animator, float defaultVal = 1.0f)
    {
        var animationClips = animator.GetNextAnimatorClipInfo(0);
        if (animationClips != null && animationClips.Length > 0)
        {
            return animationClips[0].clip.length;
        }
        return defaultVal;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,294评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,780评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,001评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,593评论 1 289
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,687评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,679评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,667评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,426评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,872评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,180评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,346评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,019评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,658评论 3 323
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,268评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,495评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,275评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,207评论 2 352

推荐阅读更多精彩内容