unity3d 常用组件扩展方法-阿里云开发者社区

开发者社区> 人工智能> 正文

unity3d 常用组件扩展方法

简介: 测试使用 using UnityEngine; using UnityEngine.UI; /// /// 测试使用 /// public class Test : MonoBehaviour { Button but; priv...

测试使用

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;
    }
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
人工智能
使用钉钉扫一扫加入圈子
+ 订阅

了解行业+人工智能最先进的技术和实践,参与行业+人工智能实践项目

其他文章