Unity构建时如何将.so库放置到Managed目录?
我来给你几个实用的解决方案,帮你摆脱每次构建Linux版本后手动移动gRPC原生库的麻烦:
方案1:用PostBuild脚本自动完成文件移动
这是最稳定的自动化方案,通过编写Unity编辑器脚本,在构建完成后自动把libgrpc_csharp_ext.x64.so从Plugins目录迁移到Managed目录。
创建一个C#脚本,把它放在Assets/Editor目录下(必须放在Editor文件夹里,否则不会触发构建回调):
using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using System.IO; public class GrpcPostBuildHandler : IPostprocessBuildWithReport { // 设置回调顺序,确保在其他构建后操作之前执行 public int callbackOrder => 1; public void OnPostprocessBuild(BuildReport report) { // 只针对Linux x64构建执行逻辑 if (report.summary.platform != BuildTarget.StandaloneLinux64) return; // 动态获取构建输出路径和应用名称,避免硬编码 string buildOutputPath = report.summary.outputPath; string appName = Path.GetFileNameWithoutExtension(buildOutputPath); // 定义源文件路径和目标文件路径 string sourceLibraryPath = Path.Combine(buildOutputPath, $"{appName}_Data/Plugins/x86_64/libgrpc_csharp_ext.x64.so"); string targetDirectory = Path.Combine(buildOutputPath, $"{appName}_Data/Managed"); string targetLibraryPath = Path.Combine(targetDirectory, "libgrpc_csharp_ext.x64.so"); // 确保目标目录存在 if (!Directory.Exists(targetDirectory)) Directory.CreateDirectory(targetDirectory); // 执行文件移动操作 if (File.Exists(sourceLibraryPath)) { // 如果目标路径已有旧文件,先删除 if (File.Exists(targetLibraryPath)) File.Delete(targetLibraryPath); File.Move(sourceLibraryPath, targetLibraryPath); Debug.Log($"✅ gRPC原生库已成功移动到: {targetLibraryPath}"); } else { Debug.LogError($"❌ 未找到gRPC原生库,路径: {sourceLibraryPath}"); } } }
之后每次构建Linux版本时,这个脚本会自动帮你完成文件迁移,完全不用手动操作。
方案2:尝试修改插件导入设置(可选,兼容性有限)
Unity默认会把Plugins目录下的原生库归类到平台专属的Plugins子目录,但你可以尝试修改导入设置,看看是否能让Unity把它放到Managed目录(注意:这个方法不一定对所有Unity版本生效,因为Unity对插件的目录规则有严格限制):
- 在Unity编辑器中选中
libgrpc_csharp_ext.x64.so文件 - 在Inspector面板中,设置Platform为
Linux,CPU为x86_64 - 尝试勾选Copy to Managed相关的选项(如果你的Unity版本有这个选项的话)
- 重新构建项目,检查文件是否被放到了Managed目录
这个方法的成功率不高,因为Unity的Managed目录主要用于存放.NET程序集,原生插件通常会被归类到Plugins目录,所以更推荐方案1。
为什么需要这么做?
gRPC的C#库在加载原生依赖时,会默认从自身Managed程序集所在的目录(也就是[app_name]_Data/Managed)查找libgrpc_csharp_ext.x64.so,但Unity的默认构建逻辑会把原生插件放到[app_name]_Data/Plugins/x86_64,这就导致gRPC找不到依赖库,所以必须把原生库移动到Managed目录才能正常运行。
内容的提问来源于stack exchange,提问作者Zane Claes
相关产品推荐
相关产品推荐

