【总】Unity Mono
2026/7/22 13:24:23 网站建设 项目流程

版本:Unity 6000.3.19f1


Debug 扩展

using System; using System.IO; using System.Text; using System.Threading.Tasks; using UnityEngine; public class DebugExtend { /// <summary> /// 是否记录日志信息 /// </summary> public static bool IsRecordLog = true; /// <summary> /// 打印日志信息 /// </summary> /// <param name="message">日志内容</param> public static async void Log(object message) { Debug.Log(message); await RecordLogInfo(message, DebugLogType.Log); } /// <summary> /// 打印日志警告信息 /// </summary> /// <param name="message">日志内容</param> public static async void LogWarning(object message) { Debug.LogWarning(message); await RecordLogInfo(message, DebugLogType.Warning); } /// <summary> /// 打印日志错误信息 /// </summary> /// <param name="message">日志内容</param> public static async void LogError(object message) { Debug.LogError(message); await RecordLogInfo(message, DebugLogType.Error); } /// <summary> /// 打印日志信息 /// </summary> /// <param name="message">日志内容</param> /// <param name="logType">打印日志类型</param> public static void Log(object message, DebugLogType logType) { switch (logType) { case DebugLogType.Log: Log(message); break; case DebugLogType.Error: LogError(message); break; case DebugLogType.Warning: LogWarning(message); break; } } /// <summary> /// 记录日志信息 /// </summary> /// <param name="message">日志内容</param> /// <param name="logType">打印日志类型</param> /// <returns></returns> private static async Task RecordLogInfo(object message, DebugLogType logType) { if (!IsRecordLog) return; // 若关闭日志输出,则不再进行记录 if (!Debug.unityLogger.logEnabled) return; string filePath = ""; string fileName = $"{logType}.txt"; string newLine = Environment.NewLine; // 换行符处理(保证跨平台兼容性) string time_stamp = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"; // 当前时间戳 string appendContent = $"[{logType.ToString().ToLower()}] {time_stamp}{newLine}{message}{newLine}{newLine}"; #if UNITY_EDITOR filePath = Path.Combine(Application.dataPath, "Editor", fileName); #elif UNITY_ANDROID || UNITY_IOS || UNITY_WEBGL filePath = Path.Combine(Application.persistentDataPath, fileName); #else filePath = Path.Combine(Environment.CurrentDirectory, fileName); #endif #if UNITY_WEBGL && !UNITY_EDITOR File.AppendAllText(filePath, appendContent, Encoding.UTF8); if (File.Exists(filePath)) Debug.Log($"Save content:\n{File.ReadAllText(filePath)}"); await Task.Delay(1); #else Debug.Log("Save file path : " + filePath); // 确保目录存在 Directory.CreateDirectory(Path.GetDirectoryName(filePath)); // 异步追加文件内容(避免主线程卡顿) await Task.Run(() => { try { #if !UNITY_ANDROID && !UNITY_IOS //// 方法一:true表示追加模式 //using (StreamWriter writer = new StreamWriter(filePath, true)) //{ // writer.Write(appendContent); //} #endif // 方法二:追加文本(如果文件不存在会自动创建),指定编码格式 File.AppendAllText(filePath, appendContent, Encoding.UTF8); } catch (Exception e) { Debug.LogError($"Unable to write log content:{e.Message}"); } }); #endif #if UNITY_EDITOR // 刷新资源数据(刷新日志信息) UnityEditor.AssetDatabase.Refresh(); #endif } } public enum DebugLogType { Log, Warning, Error }

获取本地IP

using System.Net.NetworkInformation; using System.Net.Sockets; public class MonoTools { public static string GetIP(AddressFAM addressFAM) { // https://blog.csdn.net/sinat_39291423/article/details/100733882 if (addressFAM == AddressFAM.IPv6 && !Socket.OSSupportsIPv6) { return null; } string output = ""; foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN NetworkInterfaceType _type1 = NetworkInterfaceType.Wireless80211; NetworkInterfaceType _type2 = NetworkInterfaceType.Ethernet; if ((item.NetworkInterfaceType == _type1 || item.NetworkInterfaceType == _type2) && item.OperationalStatus == OperationalStatus.Up) #endif { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (addressFAM == AddressFAM.IPv4) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { output = ip.Address.ToString(); } } else if (addressFAM == AddressFAM.IPv6) { if (ip.Address.AddressFamily == AddressFamily.InterNetworkV6) { output = ip.Address.ToString(); } } } } } return output; } public enum AddressFAM { IPv4, IPv6 } }

获取文件夹地址

using UnityEngine; public class MonoTools { public static string GetPath(ProjectPath projectPath) { string path = ""; switch (projectPath) { case ProjectPath.Assets: path = Application.dataPath; break; case ProjectPath.Data: path = Application.persistentDataPath; break; case ProjectPath.Cache: path = Application.temporaryCachePath; break; case ProjectPath.Project: path = System.Environment.CurrentDirectory; break; case ProjectPath.StreamingAssets: path = Application.streamingAssetsPath; break; } return path; } public enum ProjectPath { Project, Assets, Data, Cache, StreamingAssets } }

关闭程序(二次确定)

using System; using System.Runtime.InteropServices; using UnityEngine; public class ApplicationQuit : MonoBehaviour { #region variable /// <summary> 用于告诉Unity是否要退出 </summary> private bool m_IsWantsToQuit = false; /// <summary> 判断是否点击了退出程序按钮 </summary> private bool m_IsClickCloseBtn = false; /// <summary> 用于执行退出前的委托 </summary> private Action m_WantsToQuitAction; #endregion [DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)] public static extern int MessageBox(IntPtr handle, String message, String title, int type); private void Awake() { m_IsWantsToQuit = false; m_IsClickCloseBtn = false; Application.wantsToQuit += WantsToQuit; } private void Start() { m_WantsToQuitAction += () => ShowMessageBox(); } private bool WantsToQuit() { if (!m_IsWantsToQuit && !m_IsClickCloseBtn) m_WantsToQuitAction?.Invoke(); return m_IsWantsToQuit; } private void ShowMessageBox() { #if !UNITY_EDITOR m_IsClickCloseBtn = true; int messageIndex = MessageBox(IntPtr.Zero, "确定要退出程序吗?", "提示", 1); if (messageIndex == 1) { m_IsWantsToQuit = true; Application.Quit(); // 杀死当前进程(强制关闭) System.Diagnostics.Process.GetCurrentProcess().Kill(); } else { m_IsClickCloseBtn = false; } #endif } }

跳过启动Logo动画

using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Scripting; /// <summary> /// 项目运行初始化; /// Preserve:此特性用于防止在打包的时候这个脚本没有被打包进程序 /// </summary> [Preserve] public class RuntimeInitialize { [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)] private static void BeforeSplashScreen() { #if UNITY_WEBGL Application.focusChanged += Application_FocusChanged; #else // 跳过Unity的启动Logo System.Threading.Tasks.Task.Run(AsyncSkip); //Task.Run(() => SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate)); #endif } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] private static void BeforeSceneLoad() { Debug.Log("加载开始!!!"); } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] private static void AfterSceneLoad() { Debug.Log("加载完成!!!"); } #if UNITY_WEBGL private static void Application_FocusChanged(bool obj) { Application.focusChanged -= Application_FocusChanged; SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); } #else private static void AsyncSkip() { SplashScreen.Stop(SplashScreen.StopBehavior.StopImmediate); } #endif }

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询