Unity运行时编译程序集时自定义嵌入资源的内部存储路径
Unity 运行时动态编译嵌入资源自定义命名方案
业务场景
开发者在Unity开发中基于CSharpCodeProvider实现C#代码运行时动态编译,现有Compile方法已可正常输出目标DLL程序集,核心实现代码如下:
public void Compile() { string OutputPath = Application.dataPath + "/" + Path.Combine(Consts.OutputPath, DLLName) + ".dll"; Debug.Log(OutputPath); var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5"} }); var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll", "C:/Program Files/Unity/Editor/Data/Managed/UnityEngine.dll", Application.dataPath + "/" + Consts.IPADLLPath }, OutputPath, true); string ManifestPath = Application.dataPath + "/Exporters/manifest.json"; string ManifestJson = File.ReadAllText(ManifestPath); ManifestJson = ManifestJson.Replace("Template", DLLName); Debug.Log(ManifestJson); File.WriteAllText(ManifestPath, ManifestJson); if (csc.Supports(GeneratorSupport.Resources)) { parameters.EmbeddedResources.Add(ManifestPath); } parameters.GenerateExecutable = true; parameters.CompilerOptions = "/optimize -target:library"; string Code = Consts.BSIPAPluginStarter; List<string> Usings = new List<string>(); Usings.Add(Consts.UsingIPA); for(int i = 0; i < scriptCollection.Length; i++) { string FileStr = File.ReadAllText(Path.Combine(Application.dataPath, scriptCollection[i])); int pFrom = FileStr.IndexOf("Using ") + "Using ".Length; int pTo = FileStr.LastIndexOf(";"); string result = FileStr.Substring(pFrom-3, (pTo - pFrom)+4); Usings.Add(result); FileStr = FileStr.Remove(pFrom - 3, (pTo - pFrom) + 5); Debug.Log(FileStr); Code += FileStr; } string NewCode = ""; Usings.ForEach((string Using) => { NewCode += Using; }); NewCode += Code; Code = NewCode; Debug.Log(Code); if(File.Exists(OutputPath)) { string[] Files = Directory.EnumerateFiles(Path.GetDirectoryName(OutputPath)).Where((string path) => { return path.Contains(DLLName); }).ToArray(); for (int i = 0; i < Files.Length; i++) { Debug.Log(Files[i]); File.Delete(Files[i]); } } CompilerResults results = csc.CompileAssemblyFromSource(parameters, Code); results.Errors.Cast<CompilerError>().ToList().ForEach(error => Debug.LogError(error.ErrorText + " " + error.Line + ":" + error.Column)); EditorUtility.DisplayDialog("Export Succesful", string.Format("Exported To {0}, Remember this doesn't work for quest and will only work on pc, any object that uses the scripts you made won't have any scripts attactched to them!", OutputPath), "OK"); }
当前痛点
- 现有代码直接向
parameters.EmbeddedResources传入本地manifest.json的完整路径,编译生成的DLL里,该资源默认会以本地原文件名manifest.json为标识存在于程序集资源根路径 - 业务要求嵌入资源的命名规则为
[当前DLL名称].manifest.json,例如目标DLL为MyCustomScript.dll时,对应嵌入资源必须命名为MyCustomScript.manifest.json - 目前的临时实现是编译前将本地manifest.json重命名为目标名称,依赖本地文件名作为嵌入资源名,逻辑冗余且容易残留临时文件
- 目标需求:无需修改磁盘上的源文件名称,直接在编译阶段指定嵌入资源在程序集内部的存储标识
规范实现方式
EmbeddedResources集合的每个条目,本质是直接透传给底层csc编译器的/resource参数,完全遵循csc的参数语法规则:
- 单个参数条目格式为:
本地源文件路径,自定义程序集内资源名 - 当你只传入本地文件路径时,csc会默认取文件的短文件名作为资源名,也就是之前遇到的默认命名问题
对应代码修改仅需调整资源添加的逻辑:
if (csc.Supports(GeneratorSupport.Resources)) { // 按业务规则构造目标程序集内的资源名 string targetResourceName = $"{DLLName}.manifest.json"; // 按csc参数格式拼接本地路径+目标资源名,无需修改本地文件 parameters.EmbeddedResources.Add($"{ManifestPath},{targetResourceName}"); }
注意事项
- 该语法完全兼容代码中使用的.NET v3.5编译版本,无需调整CSharpCodeProvider的版本配置
- 若路径或资源名中包含空格,需要将整段参数用英文双引号包裹,避免编译器将空格识别为参数分隔符,参考写法:
parameters.EmbeddedResources.Add($"\"{ManifestPath}\",\"{targetResourceName}\""); - 编译完成后可通过
Assembly.LoadFrom(OutputPath).GetManifestResourceNames()校验,返回的资源名即为自定义的目标名称,效果与临时重命名文件完全一致
内容的提问来源于stack exchange,提问作者Futuremappermydud
相关产品推荐
相关产品推荐

