Version: 2021.2
public bool Build ();

返回

bool 如果构建已开始,则返回 true。如果由于编辑器当前正在编译 Assets 文件夹中的脚本而导致构建未开始,则返回 false。

描述

开始构建程序集。

构建时,Unity 主窗口右下角的小进度图标将旋转,并且 EditorApplication.isCompiling 将返回 true。

using System.IO;
using System.Linq;
using UnityEditor;
using UnityEditor.Compilation;
using UnityEngine;

public class AssembyBuilderExample { [MenuItem("AssemblyBuilder Example/Build Assembly Async")] public static void BuildAssemblyAsync() { BuildAssembly(false); }

[MenuItem("AssemblyBuilder Example/Build Assembly Sync")] public static void BuildAssemblySync() { BuildAssembly(true); }

static void BuildAssembly(bool wait) { var scripts = new[] { "Temp/MyAssembly/MyScript1.cs", "Temp/MyAssembly/MyScript2.cs" }; var outputAssembly = "Temp/MyAssembly/MyAssembly.dll"; var assemblyProjectPath = "Assets/MyAssembly.dll";

Directory.CreateDirectory("Temp/MyAssembly");

// Create scripts foreach (var scriptPath in scripts) { var scriptName = Path.GetFileNameWithoutExtension(scriptPath); File.WriteAllText(scriptPath, string.Format("using UnityEngine; public class {0} : MonoBehaviour {{ void Start() {{ Debug.Log(\"{0}\"); }} }}", scriptName)); }

var assemblyBuilder = new AssemblyBuilder(outputAssembly, scripts);

// Exclude a reference to the copy of the assembly in the Assets folder, if any. assemblyBuilder.excludeReferences = new string[] { assemblyProjectPath };

// Called on main thread assemblyBuilder.buildStarted += delegate(string assemblyPath) { Debug.LogFormat("Assembly build started for {0}", assemblyPath); };

// Called on main thread assemblyBuilder.buildFinished += delegate(string assemblyPath, CompilerMessage[] compilerMessages) { var errorCount = compilerMessages.Count(m => m.type == CompilerMessageType.Error); var warningCount = compilerMessages.Count(m => m.type == CompilerMessageType.Warning);

Debug.LogFormat("Assembly build finished for {0}", assemblyPath); Debug.LogFormat("Warnings: {0} - Errors: {0}", errorCount, warningCount);

if(errorCount == 0) { File.Copy(outputAssembly, assemblyProjectPath, true); AssetDatabase.ImportAsset(assemblyProjectPath); } };

// Start build of assembly if(!assemblyBuilder.Build()) { Debug.LogErrorFormat("Failed to start build of assembly {0}!", assemblyBuilder.assemblyPath); return; }

if(wait) { while(assemblyBuilder.status != AssemblyBuilderStatus.Finished) System.Threading.Thread.Sleep(10); } } }