unity3d 常用组件扩展方法

测试使用

using UnityEngine;
using UnityEngine.UI;

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

unity Component Extention

using UnityEngine;

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

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

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

    /// 
    /// Find with type def
    /// 
    /// 
    /// 
    /// 
    /// 
    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;
    }
    /// 
    ///  Find with type def
    /// 
    /// 
    /// 
    /// 
    /// 
    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(true))
                {
                    tran.gameObject.layer = layer;
                }
            }
        }
    }

    /// 
    /// wrapped func for destroy gameobject
    /// 
    /// 
    public static void Destroy(UnityEngine.Object obj)
    {
        if (obj != null)
        {
            if (Application.isPlaying)
            {
                UnityEngine.Object.Destroy(obj);
            }
            else
            {
                UnityEngine.Object.DestroyImmediate(obj);
            }
        }
    }

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

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

    /// 
    /// ResetTransform base info
    /// 
    /// 
    public static void ResetTransform(this GameObject go)
    {
        go.transform.ResetTransform();
    }

    /// 
    /// Temp Copy
    /// 
    /// 
    /// 
    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();
            }
        }
    }

    /// 
    /// Look At 2D Version
    /// 
    /// 
    /// 
    public static void LookAt_2D(this Transform trans, Vector3 pos)
    {
        trans.LookAt(new Vector3(pos.x, trans.position.y, pos.z));
    }
    /// 
    /// Look At Direction
    /// 
    /// 
    /// 
    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(string objectName = null, Vector3? setPos = null) where T : Component
    {
        var go = new GameObject(objectName ?? ("NewObject_" + typeof(T).Name));
        var comp = go.AddComponent();
        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;
    }
}

你可能感兴趣的:(unity3d 常用组件扩展方法)