#if UNITY_EDITOR using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using UnityEditor; using UnityEditor.PackageManager; using UnityEditor.PackageManager.Requests; using UnityEngine; using UnityEngine.Networking; // Drop this single file anywhere under Assets in a Unity 6 project. public static class ToolkitInstaller { private const string Url = "https://share.communitygametoolkit.org/toolkit/full.zip"; private const string Folder = "Community-Game-Development-Toolkit"; private const string Pending = "CommunityToolkit.InstallPending"; private static readonly string[] Packages = { "com.unity.inputsystem", "com.unity.ugui", "com.unity.render-pipelines.universal" }; private static ListRequest list; private static AddAndRemoveRequest add; private static UnityWebRequest download; private static string working; private static bool busy; [MenuItem("Game-Toolkit/Install Toolkit")] private static void Install() { if (Directory.Exists(Path.Combine(Application.dataPath, Folder)) || File.Exists(Path.Combine(Application.dataPath, Folder + ".meta"))) { EditorUtility.DisplayDialog("Install Toolkit", "The toolkit already exists in this project. Use Update Toolkit for script updates. This installer only installs into a new toolkit folder.", "OK"); return; } busy = true; SessionState.SetBool(Pending, true); StartPackageCheck(); } [MenuItem("Game-Toolkit/Install Toolkit", true)] private static bool CanInstall() => !busy && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode; [InitializeOnLoadMethod] private static void Resume() { // Package installation can reload the editor domain. Resume from a fresh package check. if (SessionState.GetBool(Pending, false)) EditorApplication.delayCall += () => { busy = true; StartPackageCheck(); }; } private static void StartPackageCheck() { try { list = Client.List(true); EditorApplication.update -= Tick; EditorApplication.update += Tick; } catch (Exception error) { Fail(error); } } private static void Tick() { try { if (list != null) { EditorUtility.DisplayProgressBar("Install Toolkit", "Checking required Unity packages…", 0.05f); if (!list.IsCompleted) return; if (list.Status == StatusCode.Failure) throw new IOException(list.Error.message); var installed = new HashSet(); foreach (var package in list.Result) installed.Add(package.name); var missing = new List(); foreach (string package in Packages) if (!installed.Contains(package)) missing.Add(package); list = null; if (missing.Count > 0) { add = Client.AddAndRemove(missing.ToArray()); return; } BeginDownload(); } if (add != null) { EditorUtility.DisplayProgressBar("Install Toolkit", "Installing required Unity packages…", 0.1f); if (!add.IsCompleted) return; if (add.Status == StatusCode.Failure) throw new IOException(add.Error.message); add = null; StartPackageCheck(); return; } if (download == null) return; if (EditorUtility.DisplayCancelableProgressBar("Install Toolkit", "Downloading toolkit and example assets…", download.downloadProgress)) { download.Abort(); Finish(); return; } if (!download.isDone) return; if (download.result != UnityWebRequest.Result.Success) throw new IOException("Download failed: " + download.error); download.Dispose(); download = null; EditorUtility.DisplayProgressBar("Install Toolkit", "Validating and unpacking toolkit…", 0.95f); string staged = Path.Combine(working, "staged"); Extract(Path.Combine(working, "full.zip"), staged); Commit(staged); Debug.Log("Toolkit installed, including example assets. Unity will now import the toolkit."); Finish(); } catch (Exception error) { Fail(error); } } private static void BeginDownload() { // A network failure is retried explicitly from the menu, rather than on every domain reload. SessionState.SetBool(Pending, false); working = Path.Combine(Path.GetFullPath("Library"), "ToolkitInstall-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(working); download = UnityWebRequest.Get(Url); download.downloadHandler = new DownloadHandlerFile(Path.Combine(working, "full.zip")); download.timeout = 600; download.SendWebRequest(); } private static void Extract(string archivePath, string staged) { var paths = new HashSet(StringComparer.OrdinalIgnoreCase); long total = 0; using (var archive = ZipFile.OpenRead(archivePath)) { if (archive.Entries.Count > 50000) throw new InvalidDataException("Too many ZIP entries."); foreach (var entry in archive.Entries) { string name = entry.FullName; if (name.EndsWith("/", StringComparison.Ordinal)) continue; ValidatePath(name); if (!paths.Add(name)) throw new InvalidDataException("Duplicate ZIP path: " + name); if (entry.Length > 512L * 1024 * 1024 || (total += entry.Length) > 2L * 1024 * 1024 * 1024) throw new InvalidDataException("The toolkit archive is too large."); string destination = Path.Combine(staged, name); Directory.CreateDirectory(Path.GetDirectoryName(destination)); using (var input = entry.Open()) using (var output = File.Create(destination)) { var buffer = new byte[65536]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { if (output.Length + read > entry.Length) throw new InvalidDataException("Invalid ZIP size."); output.Write(buffer, 0, read); } if (output.Length != entry.Length) throw new InvalidDataException("Incomplete ZIP entry."); } } } if (!File.Exists(Path.Combine(staged, Folder + ".meta")) || !File.Exists(Path.Combine(staged, Folder, "System/Editor/ToolkitUpdater.cs")) || !Directory.Exists(Path.Combine(staged, Folder, "Example Scenes"))) throw new InvalidDataException("This is not a full toolkit archive. Use full.zip, not latest.zip."); } private static void ValidatePath(string name) { if (!(name.StartsWith(Folder + "/", StringComparison.Ordinal) || name == Folder + ".meta") || name.IndexOfAny(new[] { '\\', ':', '\0' }) >= 0) throw new InvalidDataException("ZIP path outside toolkit: " + name); foreach (char character in name) if (char.IsControl(character)) throw new InvalidDataException("Control character in ZIP path."); foreach (string segment in name.Split('/')) if (segment.Length == 0 || segment.StartsWith(".", StringComparison.Ordinal) || segment.EndsWith(" ", StringComparison.Ordinal) || segment.EndsWith(".", StringComparison.Ordinal)) throw new InvalidDataException("Unsafe ZIP path: " + name); } private static void Commit(string staged) { string destination = Path.Combine(Application.dataPath, Folder); string meta = destination + ".meta"; if (Directory.Exists(destination) || File.Exists(destination) || File.Exists(meta)) throw new IOException("The toolkit destination already exists; nothing was overwritten."); bool moved = false; bool metaMoved = false; EditorApplication.LockReloadAssemblies(); AssetDatabase.DisallowAutoRefresh(); try { Directory.Move(Path.Combine(staged, Folder), destination); moved = true; File.Move(Path.Combine(staged, Folder + ".meta"), meta); metaMoved = true; } catch { if (moved) Directory.Delete(destination, true); if (metaMoved) File.Delete(meta); throw; } finally { try { AssetDatabase.AllowAutoRefresh(); AssetDatabase.Refresh(); } finally { EditorApplication.UnlockReloadAssemblies(); } } } private static void Fail(Exception error) { Debug.LogException(error); Finish(); EditorUtility.DisplayDialog("Install Toolkit", "Installation could not be completed.\n\n" + error.Message, "OK"); } private static void Finish() { EditorApplication.update -= Tick; SessionState.SetBool(Pending, false); list = null; add = null; download?.Dispose(); download = null; EditorUtility.ClearProgressBar(); busy = false; try { if (working != null && Directory.Exists(working)) Directory.Delete(working, true); } catch (Exception error) { Debug.LogWarning(error.Message); } working = null; } } #endif