为什么 Unity 在构建中包含编辑器目录

Why Unity includes the Editor directories in build

当我尝试构建我的游戏时,Unity 包含了我的 Editor 目录中的脚本。这意味着构建失败,因为 Unity.Editor 在构建期间不可访问。我正在使用 Unity 2020.1.6f1,我该如何解决这个问题?

这是我在构建过程中遇到的错误类型:

Assets\Scripts\Editor\EnemyLootEditor.cs(7,32): error CS0246: The type or namespace name 'Editor' could not be found (are you missing a using directive or an assembly reference?)

编辑器模式下启动游戏时不会出现这些错误。

这是我的 Scripts 文件夹的图片,其中包含我的所有代码文件,包括我的 Editor 文件:

存储在名为“Editor”的文件夹中的文件不包含在构建中。 (see special folder names in unity)

如果您在“常规”脚本文件中调用编辑器代码,则必须使用 UNITY_EDITOR 编译器指令将此代码括起来:

#if UNITY_EDITOR
// will not be present in build
[...]
#endif

正如@Thomas所说,是的,您必须检查您的Editor文件是否存储在Editor目录中,并在使用它们时使用编译器指令。

但这个问题似乎与程序集定义文件更相关,请查看相关的 link

Are you using assembly definition files? They don't respect Editor folders. You need to add Editor asmdefs.

总结一下,如果您的项目中有一个 .asmdef 文件,并且您正在使用编辑器脚本,则您需要 有一个 .asmdef 文件用于你的编辑器脚本.