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;
    }
}
相关文章
|
4月前
|
图形学
小功能⭐️获取Unity游戏物体上,所挂载组件的名称
小功能⭐️获取Unity游戏物体上,所挂载组件的名称
|
6月前
|
图形学
【unity小技巧】Unity人物衣服布料系统的探究 —— Cloth组件
【unity小技巧】Unity人物衣服布料系统的探究 —— Cloth组件
221 0
|
6月前
|
开发工具 图形学
【推荐100个unity插件之11】Shader实现UGUI的特效——UIEffect为 Unity UI 提供视觉效果组件
【推荐100个unity插件之11】Shader实现UGUI的特效——UIEffect为 Unity UI 提供视觉效果组件
412 0
|
7月前
|
编解码 前端开发 人机交互
【Unity 3D】UI系统中UGUI各个组件的详细讲解(附源码 超详细)
【Unity 3D】UI系统中UGUI各个组件的详细讲解(附源码 超详细)
296 0
|
7月前
|
C# 图形学
【Unity 3D】游戏对象、添加删除获取组件、预制体Prefabs简介
【Unity 3D】游戏对象、添加删除获取组件、预制体Prefabs简介
206 0
|
C# 图形学
Unity通过组件名称字符串添加脚本
通过Type.GetType(string typeName)来得到字符串对应的Type。 Type.GetType(typeName)能获取到自定义类的类型,但是获取Unity的组件不行。 例如Type.GetType(“Rigidbody”)值为null,其实是少了程序集。 string qualifiedName = typeof(Rigidbody).AssemblyQualifiedName; ty 获取Unity的组件程序集全名,再通过Type.GetType()得到的就不为null了。
497 0
Unity通过组件名称字符串添加脚本
|
编译器 图形学
Unity用脚本获取物体和组件(下)
Unity用脚本获取物体和组件(下)
273 0
|
图形学
Unity 用脚本获取物体和组件(上)
Unity 用脚本获取物体和组件(上)
319 0
|
图形学
Unity常用组件
Unity常用组件
188 0
|
前端开发 C# 开发工具
Unity快手上手【熟悉unity编辑器,C#脚本控制组件一些属性之类的】
Unity快手上手【熟悉unity编辑器,C#脚本控制组件一些属性之类的】
157 0