Unity导入GoogleMobileAds后打包Android遇UnityEditor.Build命名空间错误
解决GoogleMobileAds构建Android时Editor代码报错问题
问题现象
已将最新版GoogleMobileAds导入Unity 2021.3.30f1项目,编辑器内运行正常,但构建Android版本时,持续触发Editor文件夹下的代码错误,示例报错:
Assets\GoogleMobileAds\Editor\BuildPreProcessor.cs(5,19): error CS0234: The type or namespace name 'Build' does not exist in the namespace 'UnityEditor' (are you missing an assembly reference?)
按预期,Editor文件夹下的代码属于编辑器专属代码,构建时应被Unity自动排除,但实际未生效。
排查与解决步骤
1. 检查Editor文件夹的位置与命名
- 确认GoogleMobileAds的Editor文件夹是否为顶级目录(直接放在
Assets目录下)。如果嵌套在其他非Editor目录中,Unity可能无法识别其为编辑器专属目录,需将其移至Assets根目录。
2. 验证Assembly Definition文件配置
GoogleMobileAds的Editor目录通常自带.asmdef文件(如GoogleMobileAdsEditor.asmdef),检查该文件设置:
- 打开文件后,确认
Include Platforms仅勾选Editor,Exclude Platforms勾选所有移动端(含Android); - 确认
References中已正确添加UnityEditor和UnityEditor.Build程序集(对应报错中缺失的命名空间)。
若.asmdef文件缺失或配置错误,手动修复:
- 在Editor文件夹右键 > Create > Assembly Definition;
- 命名为
GoogleMobileAdsEditor; - 在Inspector面板设置
Include Platforms为Editor,其余平台全部排除; - 添加
UnityEditor和UnityEditor.Build到References列表。
3. 清理缓存与重新导入资源
- 执行菜单栏
Assets > Reimport All,强制重新导入所有资源; - 关闭Unity后,删除项目根目录的
Library文件夹,再重新打开Unity,让其重新生成项目缓存。
4. 检查版本兼容性
部分最新版GoogleMobileAds可能对Unity版本有隐性要求,可尝试:
- 降级GoogleMobileAds到明确支持Unity 2021.3.x的稳定版本(参考GoogleMobileAds发布说明);
- 确认Unity的Android模块安装完整,包含最新的Build Tools和SDK平台。
5. 排查自定义构建脚本
如果项目中有自定义构建脚本或预处理代码,确认它们未意外引用GoogleMobileAds的Editor代码,或在构建阶段错误包含了Editor目录资源。
内容的提问来源于stack exchange,提问作者Bjorn Fontaine
相关产品推荐
相关产品推荐

