Unity 常用扩展方法,持续更新中
这里总结了一些提高开发效率的扩展方法,放到一个类里了,可以直接拿取用,会持续更新着,也欢迎大家留言一些有用的扩展方法,大家一起维护,我更新到这个类里
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; /// <summary> /// 常用的扩展方法 /// </summary> public static class MethodExtend { #region Vector public static string ToFullString( this Vector2 v2) { return string .Format( "[{0}, {1}]" , v2.x, v2.y); } public static string ToFullString( this Vector3 v3) { return string .Format( "[{0}, {1}, {2}]" , v3.x, v3.y, v3.z); } #endregion Vector #region GameObject /// <summary> /// EventTrigger,对应拖拽、点击、鼠标在物体上等回调,用起来比较方便, /// 注意:场景中要有EventSystem,如果是3D物体,则还需要给Camera加上Physics Raycaster组件 /// </summary> public static void AddEventTrigger( this GameObject obj, EventTriggerType eventType, UnityAction<BaseEventData> callback) { EventTrigger.Entry entry = new EventTrigger.Entry(); entry.eventID = eventType; entry.callback.AddListener(callback); EventTrigger trigger = obj.GetComponent<EventTrigger>(); if (trigger == null ) { trigger = obj.AddComponent<EventTrigger>(); } trigger.triggers.Add(entry); } #endregion GameObject #region Transform public static void SetLocalPosition( this Transform transform, float x, float y, float z) { Vector3 pos = transform.localPosition; pos.Set(x, y, z); transform.localPosition = pos; } public static void SetPosition( this Transform transform, float x, float y, float z) { Vector3 pos = transform.position; pos.Set(x, y, z); transform.position = pos; } #endregion Transform #region MonoBehaviour /// <summary> /// 等待几秒执行callback /// </summary> public static Coroutine Wait( this MonoBehaviour behaviour, float time, UnityAction callback) { return behaviour.StartCoroutine(Wait(time, callback)); } /// <summary> /// 循环执行,直到callback返回true,结束循环 /// </summary> public static Coroutine Until( this MonoBehaviour behaviour, System.Func< bool > callback) { return behaviour.StartCoroutine(Until(callback)); } private static IEnumerator Wait( float time, UnityAction callback) { yield return new WaitForSeconds(time); callback?.Invoke(); } private static IEnumerator Until(System.Func< bool > callback) { if (callback != null ) { yield return new WaitUntil(callback); } } #endregion MonoBehaviour } |
博客园Jason_c微信打赏码
如果本篇文档对你有帮助,打赏Jason_c根华子吧,他的私房钱被老婆没收了,呜呜!

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2018-08-03 Unity 设置窗体透明