Unity中如何让未用#if UNITY_EDITOR的开发者提前收到编译警告?
解决Unity编辑器类调用的提前警告问题
方法1:添加占位类并触发编译错误/警告
修改ObservableEditor的定义,在非编辑器环境下生成同名占位类,通过[Obsolete]特性强制触发错误,让开发者在编写阶段就能发现问题:
#if UNITY_EDITOR using UnityEditor; public class ObservableEditor : Editor { // 编辑器逻辑代码 } #else // 非编辑器环境下的占位类,强制提示错误 [Obsolete("ObservableEditor仅支持Unity编辑器环境,请将相关调用代码用#if UNITY_EDITOR包裹", true)] public class ObservableEditor { } #endif
- 特性第二个参数设为
true时,会直接将警告升级为编译错误,确保开发者必须处理;若仅需提示警告,可改为false。 - 任何未用
#if UNITY_EDITOR包裹的ObservableEditor调用,在构建前的代码检查阶段就会触发错误,避免等到构建时才暴露问题。
方法2:编辑器扩展检测未包裹的调用
编写编辑器脚本,扫描所有引用ObservableEditor的代码文件,检查是否被预处理指令包裹,未包裹则在控制台输出警告:
#if UNITY_EDITOR using UnityEditor; using System.IO; using System.Text.RegularExpressions; public class ObservableEditorUsageChecker : AssetPostprocessor { static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { foreach (string assetPath in importedAssets) { if (!assetPath.EndsWith(".cs")) continue; string code = File.ReadAllText(assetPath); // 匹配未被#if UNITY_EDITOR包裹的ObservableEditor引用 Regex regex = new Regex(@"ObservableEditor(?!.*#if UNITY_EDITOR)", RegexOptions.Singleline); Match match = regex.Match(code); if (match.Success) { Debug.LogWarning($"文件 {assetPath} 中存在未用#if UNITY_EDITOR包裹的ObservableEditor调用,请检查代码!"); } } } } #endif
- 脚本会在每次导入/修改代码文件时自动扫描,及时给出警告提醒开发者修正。
- 注意:正则表达式需根据实际代码结构调整,避免误判。
方法3:代码规范与注释提示
在ObservableEditor类顶部添加醒目的注释,明确告知使用限制:
#if UNITY_EDITOR using UnityEditor; /// <summary> /// 仅在Unity编辑器环境下可用! /// 所有调用该类的代码必须用#if UNITY_EDITOR和#endif包裹,否则构建时会报错! /// </summary> public class ObservableEditor : Editor { // 编辑器逻辑代码 } #endif
- 结合IDE的智能提示(如VS/Rider的悬浮注释),让开发者编写代码时就能看到提示,提前规避问题。
内容的提问来源于stack exchange,提问作者TenBit
相关产品推荐
相关产品推荐

