每日一学13——Unity Debug.Log控制开关

学习来源:https://blog.youkuaiyun.com/blog_lee/article/details/81389692

其实我并不是在乎一丢丢性能的影响,我只关心能不能关闭Log,这样就可以在不想看log的时候全都不显示,不过文中的方法也不错。记录一下,没啥能改的,就不改了
开关Log

if (Debug.isDebugBuild) {
    Debug.logger.logEnabled = true;
    //Debug.logger.filterLogType = LogType.Log; //显示所有
} else {
    Debug.logger.logEnabled = false;
    //Debug.logger.filterLogType = LogType.Error;//只显示Error + Exception
}

间接调用

public static class DebugEx {
     //需要在Unity PlayerSettings -> Scripting Define Symbol 添加VERBOSE
     //Release发布时去掉VERBOSE,所有的DebugEx.Log函数调用将不会参与编译。
     //这是简单的实现方式 , 后期功能的扩展以及Debug和Release自动切换机制,可以开发者进行封装。
     [Conditional("VERBOSE")] 
     public static void Log(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.Log(message, obj);
     }
 
     public static void LogWarning(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.LogWarning(message, obj);
     }
 
     public static void LogError(object message, UnityEngine.Object obj = null) {
         UnityEngine.Debug.LogError(message, obj);
     }
 }
### 如何在 Unity 中实现 MenuItem 的开启和关闭功能 在 Unity 中,`MenuItem` 功能可以通过脚本进行动态控制。为了实现 `MenuItem` 的开启和关闭,可以利用 C# 预处理器指令以及自定义属性来管理菜单项的状态。 #### 使用预处理器指令控制 MenuItem 显示 通过使用不同的平台或环境特定的宏定义,可以在不同条件下显示或隐藏菜单项。例如: ```csharp using UnityEngine; public class MenuController : MonoBehaviour { #if UNITY_EDITOR [UnityEditor.MenuItem("Tools/MyTool/Open", false, 1)] static void OpenTool() { Debug.Log("Opening Tool"); } #if DEBUG [UnityEditor.MenuItem("Tools/MyTool/DebugFeature", false, 2)] static void EnableDebugFeature() { Debug.Log("Enabling Debug Feature"); } #endif // DEBUG #endif // UNITY_EDITOR } ``` 这段代码展示了如何基于编辑器环境 (`UNITY_EDITOR`) 和调试模式 (`DEBUG`) 来有条件地注册菜单命令[^3]。 #### 实现动态启用禁用 MenuItem 除了静态配置外,还可以编写逻辑来自动生成或移除这些条目。这通常涉及到反射机制或者直接操作内部 API 。下面是个更灵活的方法——通过设置布尔变量并将其应用于 `[MenuItem]` 属性之前: ```csharp using UnityEditor; using UnityEngine; public class DynamicMenuExample : EditorWindow { private bool _isFeatureEnabled = true; [MenuItem("Custom/Dynamic Item")] public static void ToggleDynamicItem() { var window = GetWindow<DynamicMenuExample>(); window._isFeatureEnabled = !window._isFeatureEnabled; if (_isFeatureEnabled) Menu.SetChecked("Custom/Dynamic Item", true); else Menu.SetChecked("Custom/Dynamic Item", false); Repaint(); } void OnGUI() { GUILayout.Label(_isFeatureEnabled ? "Feature Enabled" : "Feature Disabled"); if(GUILayout.Button(_isFeatureEnabled?"Disable":"Enable")) ToggleDynamicItem(); } } ``` 此示例中实现了点击按钮切换菜单项状态的效果,并且能够实时更新界面反映当前的选择情况[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值