如何自动化添加Unity Android插件依赖?现有方案问题及优化咨询
Unity Android插件依赖自动化优化方案
一、修复现有预构建脚本的痛点
针对你当前脚本存在的版本更新需手动删除旧版本、易与旧版本依赖冲突两个问题,修改脚本逻辑如下:
1. 自动替换旧版本依赖
通过正则匹配依赖的groupId和artifactId,自动替换为目标版本,无需手动删除:
using System.IO; using System.Text.RegularExpressions; using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; public class GradleTemplateModifier : IPreprocessBuildWithReport { public int callbackOrder => 0; // 统一管理需要维护的依赖(groupId:artifactId + 目标版本) private readonly (string dependencyId, string targetVersion)[] targetDependencies = { ("com.example:some-dependency", "2.0.0") }; public void OnPreprocessBuild(BuildReport report) { if (report.summary.platform != BuildTarget.Android) return; string gradleTemplatePath = "Assets/Plugins/Android/mainTemplate.gradle"; // 自动启用Custom Main Gradle Template(如果未开启) if (!File.Exists(gradleTemplatePath)) { PlayerSettings.Android.useCustomMainGradleTemplate = true; AssetDatabase.Refresh(); if (!File.Exists(gradleTemplatePath)) { Debug.LogError("Failed to generate mainTemplate.gradle, please enable it manually."); return; } } string content = File.ReadAllText(gradleTemplatePath); foreach (var (depId, targetVersion) in targetDependencies) { string fullTargetDep = $"implementation '{depId}:{targetVersion}'"; // 匹配该依赖的任意版本 string regexPattern = $@"implementation\s+'{Regex.Escape(depId)}:[^']+'"; if (Regex.IsMatch(content, regexPattern)) { // 替换旧版本为目标版本 content = Regex.Replace(content, regexPattern, fullTargetDep); Debug.Log($"Updated {depId} to version {targetVersion}"); } else { // 未找到则添加到dependencies块 int insertIndex = content.LastIndexOf("dependencies {") + "dependencies {".Length; content = content.Insert(insertIndex, $"\n\t{fullTargetDep}"); Debug.Log($"Added dependency: {fullTargetDep}"); } } File.WriteAllText(gradleTemplatePath, content); AssetDatabase.Refresh(); } }
2. 强制解决依赖冲突
在依赖声明中加入force = true,强制使用你指定的版本,覆盖项目中其他旧版本依赖:
// 修改fullTargetDep为带强制声明的版本 string fullTargetDep = $"implementation '{depId}:{targetVersion}' {{ force = true }}";
二、Unity内置的更简便方案
无需修改mainTemplate.gradle,直接用Unity官方API实现依赖自动化,避免模板篡改问题:
1. 使用PlayerSettings.additionalGradleDependencies
Unity允许通过代码直接向生成的gradle文件注入依赖,无需启用自定义模板:
using UnityEditor; using UnityEditor.Build; using UnityEditor.Build.Reporting; using UnityEngine; public class AndroidDependencyAutoSetup : IPreprocessBuildWithReport { public int callbackOrder => 1; private const string TargetDependency = "com.example:some-dependency:2.0.0"; private const string DepId = "com.example:some-dependency"; public void OnPreprocessBuild(BuildReport report) { if (report.summary.platform != BuildTarget.Android) return; string currentDeps = PlayerSettings.Android.additionalGradleDependencies; bool hasOldVersion = currentDeps.Contains(DepId) && !currentDeps.Contains(TargetDependency); // 移除旧版本依赖 if (hasOldVersion) { string[] lines = currentDeps.Split('\n'); var filteredLines = new System.Collections.Generic.List<string>(); foreach (var line in lines) { if (!line.Contains(DepId)) filteredLines.Add(line); } currentDeps = string.Join("\n", filteredLines); } // 添加/更新目标依赖 if (!currentDeps.Contains(TargetDependency)) { currentDeps += $"\n{TargetDependency}"; PlayerSettings.Android.additionalGradleDependencies = currentDeps; Debug.Log("Added/updated dependency via PlayerSettings"); } } }
这种方式的优势:
- 无需手动启用或修改任何gradle模板
- 依赖直接注入到Unity生成的gradle文件,不会修改项目内的模板资源
- 版本更新仅需修改
TargetDependency常量即可
2. 轻量配置:Gradle Properties传递依赖
如果需要更灵活的版本管理,可以通过Gradle Properties传递配置:
// 在脚本中添加gradle属性 PlayerSettings.Android.additionalGradleProperties += "\nmyPluginDependency=com.example:some-dependency:2.0.0";
然后在mainTemplate.gradle中引用(需先启用Custom Main Gradle Template):
dependencies { implementation project(':unityLibrary') implementation properties('myPluginDependency') }
后续更新版本时,只需修改属性值即可,无需改动gradle模板内容。
三、额外优化建议
- 若开发的是可分发插件,建议通过
AssetPostprocessor在插件导入时自动执行依赖配置,而非仅在构建前触发 - 批量解决冲突时,可在gradle模板中添加版本统一策略:
configurations.all { resolutionStrategy { force 'com.example:some-dependency:2.0.0' } }
这段代码也可以通过脚本自动注入到mainTemplate.gradle中。
内容的提问来源于stack exchange,提问作者Naor Geva
相关产品推荐
相关产品推荐

