### One-minute setup with filters and depth limits Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Relational-Components-Relational-Components Shows a quick setup using attributes with optional parameters like OnlyAncestors, OnlyDescendants, and MaxDepth to control the search. This example demonstrates how to configure the attributes for more specific component resolution. ```csharp [SiblingComponent] private SpriteRenderer sprite; [ParentComponent(OnlyAncestors = true)] private Rigidbody2D rb; [ChildComponent(OnlyDescendants = true, MaxDepth = 1)] private Collider2D[] childColliders; void Awake() => this.AssignRelationalComponents(); ``` -------------------------------- ### EnemyFactory with AssignRelationalComponents and binding Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/Samples~/DI - Zenject/README.md Advanced example for custom factories, showing how to override Create() to assign relational components and bind the factory in an installer. ```csharp public class EnemyFactory : PlaceholderFactory { [Inject] private DiContainer _container; public override Enemy Create() { Enemy enemy = base.Create(); _container.AssignRelationalComponents(enemy); return enemy; } } // In your installer: Container.BindFactory() .FromComponentInNewPrefab(enemyPrefab); ``` -------------------------------- ### Quick Start: Multiple Inspector Features Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Inspector-Overview Complete example combining WGroup, WShowIf, WEnumToggleButtons, SerializableDictionary, WGuid, and WButton. Use as a reference for setting up a MonoBehaviour with grouped fields, conditional visibility, toggle buttons, and serializable collections. ```csharp using UnityEngine; using WallstopStudios.UnityHelpers.Core.Attributes; using WallstopStudios.UnityHelpers.Core.DataStructure.Adapters; public class CharacterStats : MonoBehaviour { // Grouped fields with collapsible sections [WGroup("Combat", "Combat Stats", collapsible: true)] public float maxHealth = 100f; // In group public float defense = 10f; // In group (auto-included) [WGroupEnd("Combat")] // attackPower IS included, then closes public float attackPower = 25f; // In group (last field) // Conditional visibility based on enum public enum WeaponType { Melee, Ranged, Magic } public WeaponType weaponType; [WShowIf(nameof(weaponType), WShowIfComparison.Equal, WeaponType.Ranged)] public int ammoCapacity = 30; // Flag enum as toggle buttons [System.Flags] public enum Abilities { None = 0, Jump = 1, Dash = 2, Block = 4 } [WEnumToggleButtons(showSelectAll: true)] public Abilities unlockedAbilities; // Serializable collections public SerializableDictionary stats; public WGuid entityId = WGuid.NewGuid(); // Inspector button [WButton("Reset Stats")] private void ResetStats() => maxHealth = defense = attackPower = 100f; } ``` -------------------------------- ### Creating GUIDs with WGuid Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Serialization-Serialization-Types Demonstrates various ways to create WGuid instances: generating new, converting from System.Guid, parsing from string, safe try-parse, and getting the empty GUID. ```csharp // Generate new GUID WGuid id1 = WGuid.NewGuid(); // From System.Guid System.Guid sysGuid = System.Guid.NewGuid(); WGuid id2 = (WGuid)sysGuid; // Parse from string WGuid id3 = WGuid.Parse("12345678-1234-1234-1234-123456789abc"); // Try parse (safe) if (WGuid.TryParse("...", out WGuid id4)) { Debug.Log($"Parsed: {id4}"); } // Empty GUID WGuid empty = WGuid.EmptyGuid; ``` -------------------------------- ### Prefab Instantiation with Reflex DI and Relational Components Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/Samples~/DI - Reflex/README.md Use this snippet to spawn prefabs at runtime with automatic dependency injection and relational component wiring. It shows how to get the scene container, instantiate a component or GameObject with relations, and hydrate an existing GameObject. The example includes options like includeInactiveChildren. ```csharp using UnityEngine; using Reflex.Core; using Reflex.Extensions; using WallstopStudios.UnityHelpers.Integrations.Reflex; public sealed class EnemySpawner : MonoBehaviour { [SerializeField] private Enemy _enemyPrefab; [SerializeField] private GameObject _enemySquadPrefab; private Container _container; private void Awake() { _container = gameObject.scene.GetSceneContainer(); } public Enemy SpawnEnemy(Transform parent) { return _container.InstantiateComponentWithRelations(_enemyPrefab, parent); } public GameObject SpawnEnemySquad(Transform parent) { return _container.InstantiateGameObjectWithRelations( _enemySquadPrefab, parent, includeInactiveChildren: true ); } public void HydrateExisting(GameObject root) { _container.InjectGameObjectWithRelations(root, includeInactiveChildren: true); } } ``` -------------------------------- ### Install Unity Pipeline package Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/scripts/mcp/README.md Run `unity pipeline install --project-path ` on the host to install the Pipeline package. Then confirm `unity status` and `unity list --project-path ` return a nonempty catalog, and check compilation. ```bash unity pipeline install --project-path ``` ```bash unity status ``` ```bash unity list --project-path ``` -------------------------------- ### LevelManager: Complete Example with All Parameter Features Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Inspector-Button Shows a MonoBehaviour with WButton attributes using groupPriority, groupPlacement, historyCapacity, and colorKey parameters. Demonstrates how buttons are grouped and ordered in the inspector, with Setup and Debug groups at the top, and Actions and Maintenance groups at the bottom. ```csharp using UnityEngine; using WallstopStudios.UnityHelpers.Core.Attributes; public class LevelManager : MonoBehaviour { public int currentLevel = 1; public bool debugMode = false; // Setup group - explicitly placed at top, renders first due to groupPriority: 0 [WButton("Initialize Level", groupName: "Setup", groupPriority: 0, groupPlacement: WButtonGroupPlacement.Top)] private void Initialize() { Debug.Log("Level initialized!"); } [WButton("✓ Validate Configuration", groupName: "Setup")] private void ValidateConfig() { Debug.Log("Configuration valid!"); } // Debug group - explicitly placed at top, renders second due to groupPriority: 1 [WButton("Roll Dice", historyCapacity: 10, groupName: "Debug", groupPriority: 1, groupPlacement: WButtonGroupPlacement.Top)] private int RollDice() => Random.Range(1, 7); [WButton("🎯 Spawn Test Enemy", colorKey: "Warning", groupName: "Debug")] private void SpawnTestEnemy() { // Spawn logic here } // Properties appear here in the inspector // Actions group - explicitly placed at bottom, renders first in bottom section due to groupPriority: 0 [WButton("▶ Start Level", colorKey: "Success", groupName: "Actions", groupPriority: 0, groupPlacement: WButtonGroupPlacement.Bottom)] private void StartLevel() { Debug.Log($"Starting level {currentLevel}..."); } [WButton("⏸ Pause Game", groupName: "Actions")] private void PauseGame() { Time.timeScale = 0f; } [WButton("🔄 Restart Level", colorKey: "Danger", groupName: "Actions")] private void RestartLevel() { // Restart logic here } // Maintenance group - explicitly placed at bottom, renders last in bottom section due to groupPriority: 10 [WButton("Clear Cache", historyCapacity: 1, groupName: "Maintenance", groupPriority: 10, groupPlacement: WButtonGroupPlacement.Bottom)] private string ClearCache() { return $"Cache cleared at {System.DateTime.Now:HH:mm:ss}"; } } ``` -------------------------------- ### Quick start examples for VContainer, Zenject, and Reflex Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/README.md Shows how to register relational components in VContainer's LifetimeScope, and how to instantiate prefabs with DI and relations in Zenject and Reflex. VContainer uses RegisterRelationalComponents with options and additive scene listener; Zenject and Reflex use InstantiateComponentWithRelations. ```csharp // VContainer: LifetimeScope using VContainer; using VContainer.Unity; using WallstopStudios.UnityHelpers.Integrations.VContainer; protected override void Configure(IContainerBuilder builder) { // Register assigner + one-time scene scan + additive listener (default) builder.RegisterRelationalComponents( RelationalSceneAssignmentOptions.Default, enableAdditiveSceneListener: true ); } // Zenject: prefab instantiation with DI + relations using Zenject; using WallstopStudios.UnityHelpers.Integrations.Zenject; var enemy = Container.InstantiateComponentWithRelations(enemyPrefab, parent); // Reflex: prefab instantiation with DI + relations using Reflex.Core; using WallstopStudios.UnityHelpers.Integrations.Reflex; var enemy = container.InstantiateComponentWithRelations(enemyPrefab, parent); ``` -------------------------------- ### Install Unity Helpers via OpenUPM CLI Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/README.md Use the OpenUPM CLI to add the Unity Helpers package. Requires the OpenUPM CLI to be installed. ```bash openupm add com.wallstop-studios.unity-helpers ``` -------------------------------- ### Pooling utilities usage examples Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Home Examples of acquiring pooled collections and arrays using Buffers, WallstopArrayPool, and WallstopFastArrayPool. These are one-liners showing the lease pattern. ```csharp using var lease = Buffers.List.Get(out List list); ``` ```csharp using var lease = Buffers.Stack.Get(out Stack stack); ``` ```csharp using var lease = Buffers.HashSet.Get(out HashSet set); ``` ```csharp using var lease = WallstopArrayPool.Get(1024, out int[] buffer); ``` ```csharp using var lease = WallstopFastArrayPool.Get(count, out int[] buffer); ``` -------------------------------- ### RuntimeSingleton simple service example Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Singletons Shows a minimal service class deriving from RuntimeSingleton with Preserve disabled and a usage example. Access via GameServices.Instance; the singleton is created on demand if none exists. ```csharp using UnityEngine; using WallstopStudios.UnityHelpers.Utils; public sealed class GameServices : RuntimeSingleton { // Disable cross‑scene persistence if desired protected override bool Preserve => false; public void Log(string message) { Debug.Log($"[GameServices] {message}"); } } // Usage from anywhere GameServices.Instance.Log("Hello world"); ``` -------------------------------- ### Opt-in MCP server setup commands Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Mcp-Ecosystem Commands to add optional MCP servers to your client config. Serena requires dotnet 10 SDK and Unity-generated .csproj/.sln files. Playwright requires a one-time browser install. Semgrep provides seven security scanning tools. Keep tool counts trimmed server-side before client-side filters. ```bash # Serena: semantic C# tools + project memories (requires dotnet 10 SDK for Roslyn LS, # and Unity-generated .csproj/.sln files for C# resolution) uvx --from git+https://github.com/oraios/serena serena start-mcp-server --context ide-assistant # Playwright MCP: headless browser automation for the rendered docs site npx @playwright/mcp@latest --headless # once: npx playwright install --with-deps chromium # Semgrep MCP: agent-driven security scanning (seven tools) uvx semgrep-mcp ``` -------------------------------- ### Git URL for versioned installation Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Project-Contributing Use this Git URL format to install a specific version of the unity-helpers package. The version tag must not include a 'v' prefix. ```text https://github.com/wallstop/unity-helpers.git#3.1.5 ``` -------------------------------- ### Install Unity Helpers via Git URL in manifest.json Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/README.md Add the Git URL dependency to Packages/manifest.json to install the latest version directly from GitHub. Append #3.1.0 to lock to a specific version. ```json { "dependencies": { "com.wallstop-studios.unity-helpers": "https://github.com/wallstop/unity-helpers.git" } } ``` -------------------------------- ### Set up Python environment and build docs Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Project-Contributing Creates a virtual environment with Python 3.11, installs dependencies from the lock file, and builds the documentation with strict mode. ```bash uv venv .venv --python 3.11 uv pip install --python .venv/bin/python -r requirements-docs.lock .venv/bin/mkdocs build --strict ``` -------------------------------- ### Setup and usage of unlock effects with tags Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Effects-Effects-System Shows how to set up infinite duration effects as unlock flags and use them across game systems (abilities, level gates, UI, save/load). The code includes asset setup comments and C# examples for PlayerAbilities, DungeonGate, MainMenuUI, and SaveSystem. ```csharp // === Setup unlock effects === // UnlockDoubleJump.asset: // - durationType: Infinite (permanent unlock) // - effectTags: ["CanDoubleJump", "HasUpgrade"] // QuestKeyItem.asset: // - durationType: Infinite // - effectTags: ["HasKeyItem", "CanEnterDungeon"] // TutorialComplete.asset: // - durationType: Infinite // - effectTags: ["TutorialComplete", "CanAccessMultiplayer"] // === Usage throughout game systems === // Ability system public class PlayerAbilities : MonoBehaviour { void Update() { // Jump if (Input.GetKeyDown(KeyCode.Space)) { if (isGrounded) { Jump(); } // Double jump only works if unlocked else if (this.HasTag("CanDoubleJump") && !hasUsedDoubleJump) { Jump(); hasUsedDoubleJump = true; } } // Dash if (Input.GetKeyDown(KeyCode.LeftShift)) { if (this.HasTag("CanDash")) { Dash(); } else { ShowMessage("Unlock dash ability first!"); } } } } // Level gate public class DungeonGate : MonoBehaviour { void OnTriggerEnter2D(Collider2D other) { GameObject player = other.gameObject; if (player.HasTag("HasKeyItem")) { // Has the key - open gate OpenGate(); } else { // Missing key - show hint ShowMessage("You need the Ancient Key to enter."); } } } // UI system public class MainMenuUI : MonoBehaviour { [SerializeField] private Button multiplayerButton; void Update() { // Disable multiplayer until tutorial is complete multiplayerButton.interactable = player.HasTag("TutorialComplete"); } } // Save system public class SaveSystem : MonoBehaviour { public SaveData CreateSaveData(GameObject player) { // Save all permanent unlocks var saveData = new SaveData { unlockedAbilities = new List() }; // Check all capability tags if (player.HasTag("CanDoubleJump")) saveData.unlockedAbilities.Add("DoubleJump"); if (player.HasTag("CanDash")) saveData.unlockedAbilities.Add("Dash"); if (player.HasTag("HasKeyItem")) saveData.unlockedAbilities.Add("KeyItem"); return saveData; } public void LoadSaveData(GameObject player, SaveData saveData) { // Reapply permanent unlocks foreach (string ability in saveData.unlockedAbilities) { AttributeEffect unlock = LoadUnlockEffect(ability); player.ApplyEffect(unlock); } } } ``` -------------------------------- ### BrowserStorage Usage Example Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/docs/features/utilities/helper-utilities.md Demonstrates creating a BrowserStorage instance and using its TrySetString, TryGetString, and TryDeleteKey methods. ```APIDOC ## BrowserStorage ### Description Provides scoped string storage. WebGL players use the browser's localStorage; editor and other players use PlayerPrefs. Backend selection happens at compile time. ### Methods #### TrySetString Sets a string value for a given key within the storage scope. - **Parameters**: - `key` (string) - The literal, case-sensitive key. Must be non-null and non-empty. Whitespace keys are valid. - `value` (string) - The string value to store. Must not contain null characters or unpaired UTF-16 surrogates. - **Returns**: `bool` - True if the operation succeeded; false if the scope is invalid, the key or value is invalid, or the backend fails. #### TryGetString Gets a string value for a given key within the storage scope. - **Parameters**: - `key` (string) - The literal, case-sensitive key. Must be non-null and non-empty. - `value` (out string) - When this method returns, contains the value associated with the key, if the key is found; otherwise, null. - **Returns**: `bool` - True if the key exists and the value is retrieved; false if the key is missing, the scope is invalid, or the backend fails. #### TryDeleteKey Deletes a key and its associated value from the storage scope. - **Parameters**: - `key` (string) - The literal, case-sensitive key to delete. Must be non-null and non-empty. - **Returns**: `bool` - True if the deletion succeeded; false if the scope is invalid, the key is invalid, or the backend fails. ### Usage Example ```csharp using WallstopStudios.UnityHelpers.Core.Helper; BrowserStorage storage = new BrowserStorage("my-game"); if (storage.TrySetString("settings", "volume=0.5") && storage.TryGetString("settings", out string settings)) { UnityEngine.Debug.Log(settings); } storage.TryDeleteKey("settings"); ``` ### Remarks - Call these methods on Unity's main thread. - A scope must be nonblank; invalid scopes produce a store with `IsConfigured == false` whose operations return false. - Keys are literal, case-sensitive strings; whitespace keys are valid, null and empty keys are rejected. - Different scopes cannot alias each other's keys, even when scopes or keys contain colons. - The store never clears all browser or PlayerPrefs data. - Null values, null characters and unpaired UTF-16 surrogates in keys, scopes or values are rejected; invalid writes leave existing values unchanged. - Reads return false with a null result when a key is missing or the backend fails. Present empty strings return true. - Browser values containing invalid text written by another application are rejected rather than silently truncated by the native string bridge. - Writes and deletes are synchronous browser operations. The PlayerPrefs backend calls `Save` after each mutation. - Success means the backend accepted the operation; it does not guarantee disk flush, future availability, cross-tab transactions or protection from browser eviction. - If PlayerPrefs saving fails, its in-memory mutation may already have happened. - Use an application-specific scope on shared origins. Stored strings are not encrypted. - Private browsing, denied storage access and quotas can cause failure. - Each operation constructs a scoped key, and reads allocate their returned string. ``` -------------------------------- ### Intermediate Example: ProjectileSpawner with InstantiateComponentWithRelations Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/Samples~/DI - Reflex/README.md Shows runtime instantiation using _container.InstantiateComponentWithRelations to inject dependencies and wire hierarchy automatically. Requires getting the scene container in Awake. ```csharp public sealed class ProjectileSpawner : MonoBehaviour { private Container _container; [SerializeField] private Projectile _projectilePrefab; private void Awake() { _container = gameObject.scene.GetSceneContainer(); } public Projectile Fire(Vector3 position, Vector3 direction) { Projectile projectile = _container.InstantiateComponentWithRelations(_projectilePrefab); projectile.transform.SetPositionAndRotation(position, Quaternion.LookRotation(direction)); projectile.Launch(direction); return projectile; } } ``` -------------------------------- ### Set up Unity license with npm run unity:setup-license Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Unity-Devcontainer-Licensing Writes .unity-secrets/credentials.env (gitignored), which run-unity-docker.sh loads when the environment variables are not already set. ```bash npm run unity:setup-license ``` -------------------------------- ### Protobuf Serialization Example Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/README.md Shows how to use protobuf-net for compact binary serialization. Includes a [ProtoContract] class, serialization/deserialization, generic entry points, and buffer reuse to reduce GC. ```csharp using ProtoBuf; // protobuf-net using UnityEngine; using WallstopStudios.UnityHelpers.Core.Serialization; [ProtoContract] public class NetworkMessage { [ProtoMember(1)] public int playerId; [ProtoMember(2)] public Vector3 position; // Vector3 works in Protobuf via built-in surrogates } var message = new NetworkMessage { playerId = 7, position = new Vector3(5, 0, -2) }; // Protobuf bytes (small + fast) byte[] bytes = Serializer.ProtoSerialize(message); NetworkMessage decoded = Serializer.ProtoDeserialize(bytes); // Generic entry points byte[] bytes2 = Serializer.Serialize(message, SerializationType.Protobuf); NetworkMessage decoded2 = Serializer.Deserialize(bytes2, SerializationType.Protobuf); // Buffer reuse (reduce GC for hot paths) byte[] buffer = null; int len = Serializer.Serialize(message, SerializationType.Protobuf, ref buffer); NetworkMessage again = Serializer.Deserialize(buffer.AsSpan(0, len).ToArray(), SerializationType.Protobuf); ``` -------------------------------- ### Parent traversal - find component in parents and get all parents Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Helper-Utilities Walks up the hierarchy. The first example uses Helpers.IterateOverAllParentComponentsRecursively to find a Canvas component in parents. The second uses Helpers.IterateOverAllParents with a buffer to get all parent transforms up to the root. Useful for finding UI Canvas parents, inheritance checking, and walking to root. ```csharp using WallstopStudios.UnityHelpers.Core.Helper; // Find component in parents Helpers.IterateOverAllParentComponentsRecursively(transform, canvas => { Debug.Log($"Found canvas: {canvas.name}"); }); // Get all parents (no component filter) using (var buffer = Buffers.List.Get()) { Helpers.IterateOverAllParents(transform, buffer.Value); // buffer contains all parent transforms up to root } ``` -------------------------------- ### Chi-Square Survival with WallMath.TryChiSquareSurvival Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Helper-Utilities Gets the upper-tail probability for a chi-square statistic. Returns false for negative or NaN statistics. The example with statistic 3.841458820694124 and 1 degree of freedom yields about 0.05. ```csharp using WallstopStudios.UnityHelpers.Core.Helper; bool evaluated = WallMath.TryChiSquareSurvival( statistic: 3.841458820694124, degreesOfFreedom: 1, out double upperTailProbability ); // about 0.05 ``` -------------------------------- ### Line2D.TryGetIntersectionPoint(Circle, out Vector2) Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/docs/features/utilities/math-and-extensions.md Attempts to get the first point on the circumference of a circle that the line segment intersects, ordered from the line's start to end. Returns true if the line crosses the circle's circumference. ```APIDOC ## Line2D.TryGetIntersectionPoint(Circle, out Vector2) ### Description Attempts to get the first point on the circumference of a circle that the line segment intersects, ordered from the line's start to end. Returns true if the line crosses the circle's circumference. ### Method TryGetIntersectionPoint ### Signature `bool TryGetIntersectionPoint(Circle circle, out Vector2 intersectionPoint)` ### Parameters - **circle** (Circle) - Required - The circle to test intersection with. - **intersectionPoint** (out Vector2) - Required - The first intersection point on the circumference, ordered from the line's start to end. ### Returns - **bool** - True if the line segment crosses the circle's circumference, false otherwise. ### Remarks - Rejects negative radii. - A path wholly inside the circle intersects its area but does not cross its circumference, so this method returns false in that case. ### Example ```csharp var bulletPath = new Line2D(bulletStart, bulletEnd); var enemy = new Circle(enemyPosition, enemyRadius); if (bulletPath.TryGetIntersectionPoint(enemy, out Vector2 hitPoint)) { impactEffect.transform.position = hitPoint; enemy.TakeDamage(bulletDamage); } ``` ``` -------------------------------- ### Range inclusivity options Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Math-And-Extensions Shows three boundary configurations: Inclusive (closed interval), InclusiveExclusive (start included, end excluded), and Exclusive (open interval). Each example demonstrates Contains behavior for endpoints and interior values. ```csharp // [0, 10] - both endpoints included (closed interval) var healthRange = Range.Inclusive(0, 10); healthRange.Contains(0); // true healthRange.Contains(10); // true // [0, 10) - start included, end excluded (common for indices) var arrayRange = Range.InclusiveExclusive(0, 10); arrayRange.Contains(0); // true arrayRange.Contains(10); // false (typical for array[0..10)) // (0, 1) - neither endpoint included (open interval) var normalized = Range.Exclusive(0f, 1f); normalized.Contains(0f); // false normalized.Contains(0.5f); // true normalized.Contains(1f); // false ``` -------------------------------- ### Complete Migration Example - Before (Odin) Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Odin-Migration-Guide Original Odin-based EnemySpawner class using SerializedMonoBehaviour and various Odin attributes. ```csharp using Sirenix.OdinInspector; using Sirenix.Serialization; using UnityEngine; using System.Collections.Generic; public class EnemySpawner : SerializedMonoBehaviour { [BoxGroup("Settings")] [Required] public GameObject enemyPrefab; [BoxGroup("Settings")] [ShowIf("useWaves")] public int wavesCount = 3; public bool useWaves; [EnumToggleButtons] public SpawnPattern pattern; [ValueDropdown("GetSpawnRates")] public float spawnRate; public Dictionary enemyWeights; [Button("Spawn Wave")] private void SpawnWave() { } private float[] GetSpawnRates() => new[] { 0.5f, 1f, 2f }; } ``` -------------------------------- ### BrowserStorage usage example Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Helper-Utilities Creates a BrowserStorage instance with a scope, sets and gets a string, then deletes the key. Operations are synchronous and must be called on the main thread. Invalid scopes or keys cause operations to return false. ```csharp using WallstopStudios.UnityHelpers.Core.Helper; BrowserStorage storage = new BrowserStorage("my-game"); if (storage.TrySetString("settings", "volume=0.5") && storage.TryGetString("settings", out string settings)) { UnityEngine.Debug.Log(settings); } storage.TryDeleteKey("settings"); ``` -------------------------------- ### IntMap usage example in C# Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Data-Structures Shows how to create an IntMap, set and get values, overwrite in place, and remove entries. Note that the two lowest key values are reserved and refused by TrySet without throwing. ```csharp using WallstopStudios.UnityHelpers.Core.DataStructure; var map = new IntMap(); map.TrySet(entityId, HealthState.Poisoned); if (map.TryGet(entityId, out HealthState state)) { /* ... */ } map.TrySet(entityId, HealthState.Healthy); // overwrite in place map.Remove(entityId, out _); // closes the probe-chain gap without allocating ``` -------------------------------- ### Install via Git URL Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Index In Unity Package Manager, click 'Add package from git URL' and enter the repository URL. ```text https://github.com/wallstop/unity-helpers.git ``` -------------------------------- ### SerializableType create, resolve, check, and equality operations Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Serialization-Serialization-Types Shows the core SerializableType operations: creating from a Type, resolving to a Type, checking emptiness, getting a display name, and equality comparison. The example defines a PlayerController class for demonstration. ```csharp public sealed class PlayerController : MonoBehaviour { } // Create SerializableType typeRef = new SerializableType(typeof(PlayerController)); // Resolve Type resolvedType = typeRef.Value; if (resolvedType != null) { object instance = Activator.CreateInstance(resolvedType); } // Check bool isEmpty = typeRef.IsEmpty; string displayName = typeRef.DisplayName; // User-friendly name // Equality bool equal = typeRef.Equals(new SerializableType(typeof(PlayerController))); ``` -------------------------------- ### Quick Start: Using PRNG.Instance for random generation Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Random-Generators Use the thread-local default PRNG.Instance for fast random generation. Demonstrates basic integer, float, bool, and uint generation, plus Unity vectors, colors, weighted selection, and Gaussian distribution. ```csharp using WallstopStudios.UnityHelpers.Core.Random; // Use the thread-local default (fastest) IRandom random = PRNG.Instance; // Basic generation int number = random.Next(0, 100); // [0, 100) float value = random.NextFloat(); // [0.0, 1.0) bool coinFlip = random.NextBool(); uint bits = random.NextUint(); // Unity vectors Vector2 point2D = random.NextVector2(-10f, 10f); // Colors Color randomColor = random.NextColor(); // Weighted selection string[] items = { "Common", "Rare", "Epic" }; float[] weights = { 70f, 25f, 5f }; string selected = random.NextWeighted(items.Zip(weights, (x, y) => (x, y))); // Gaussian distribution float normalValue = random.NextGaussian(mean: 0f, stdDev: 1f); ``` -------------------------------- ### TryApplyDictionaryMigration(preview, compilation, out apply, out failure) Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Odin-Migration-Guide Starts a paired source and retained-data migration after checking a successful, matching compilation receipt and a fresh complete inventory. It currently refuses affected documents without retained payloads. ```APIDOC ## TryApplyDictionaryMigration(preview, compilation, out apply, out failure) ### Description Starts a paired source and retained-data migration after checking a successful, matching compilation receipt and a fresh complete inventory. It currently refuses affected documents without retained payloads. ### Method TryApplyDictionaryMigration ### Parameters - **preview** - The preview to apply. - **compilation** - The compilation receipt to validate. - **apply** (out) - The apply result. - **failure** (out) - The failure information if the operation fails. ### Returns - **bool** - True if the apply succeeds; otherwise false. ``` -------------------------------- ### Register custom tag decoration with AddDecoration Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Logging-Logging-Extensions Registers a custom tag decoration for tags starting with 'stat:' using a predicate and format function. The example is intended for an InitializeOnLoad editor script or runtime bootstrapper. It uses a negative priority to run before built-in decorations. ```csharp using WallstopStudios.UnityHelpers.Core.Extension; using WallstopStudios.UnityHelpers.Core.Helper.Logging; [InitializeOnLoad] internal static class LoggingBootstrap { static LoggingBootstrap() { UnityLogTagFormatter formatter = WallstopStudiosLogger.LogInstance; formatter.AddDecoration( predicate: tag => tag.StartsWith("stat:", StringComparison.OrdinalIgnoreCase), format: (tag, value) => { string label = tag.Substring("stat:".Length); return $"[{label}] {value}"; }, tag: "StatLabel", priority: -10 // run before built-ins ); } } ``` -------------------------------- ### Post: Async version with result from main thread Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Helper-Utilities Use this when you need to get a return value from code executed on the main thread. The example shows awaiting UnityMainThreadDispatcher.Instance.Post with a lambda that returns a string, allowing safe access to Unity objects from a background thread. ```csharp async Task GetTextFromMainThread() { // Called from background thread, executes on main thread string text = await UnityMainThreadDispatcher.Instance.Post(() => { return uiText.text; // Safe to access Unity objects }); return text; } ``` -------------------------------- ### Configure and use GlobalPoolRegistry Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Pooling-Guide Shows how to set the global budget, retrieve statistics, and enforce the budget. Use TryEnforceBudgetIfNeeded for a non-blocking check that purges items only when over budget. ```csharp using WallstopStudios.UnityHelpers.Utils; // Configure global budget PoolPurgeSettings.GlobalMaxPooledItems = 50000; // Get global statistics GlobalPoolStatistics globalStats = GlobalPoolRegistry.GetStatistics(); int totalPooled = globalStats.TotalPooledItems; float budgetUtilization = globalStats.BudgetUtilization; int registeredPools = globalStats.RegisteredPoolCount; // Force budget enforcement GlobalPoolRegistry.EnforceBudget(); // Try non-blocking budget check if (GlobalPoolRegistry.TryEnforceBudgetIfNeeded()) { // Budget was over, items purged } ``` -------------------------------- ### WGuid conversions to and from System.Guid Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Serialization-Serialization-Types Shows how to convert between WGuid and System.Guid, and how to use ToString() with different format specifiers. ```csharp // WGuid <-> System.Guid WGuid wguid = WGuid.NewGuid(); System.Guid sysGuid = wguid.ToGuid(); WGuid back = (WGuid)sysGuid; // ToString() formats string standard = wguid.ToString(); // "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" string formatted = wguid.ToString("N"); // Without hyphens ``` -------------------------------- ### Prewarm reflection caches with RelationalComponentInitializer.Initialize Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/Samples~/DI - Zenject/README.md Call RelationalComponentInitializer.Initialize once during bootstrap to prewarm reflection caches and avoid first-use stalls. Bind GameBootstrap as single in installer. ```csharp using WallstopStudios.UnityHelpers.Core.Attributes; public class GameBootstrap : IInitializable { public void Initialize() { // Call once during bootstrap/loading screen RelationalComponentInitializer.Initialize(); } } // In your installer: Container.BindInterfacesTo().AsSingle(); ``` -------------------------------- ### Configure per-pool options with PoolOptions Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Pooling-Guide Shows how to create a PoolOptions instance with various settings such as size limits, timing, intelligent purging, triggers, and callbacks, and then pass it to a WallstopGenericPool constructor. ```csharp using WallstopStudios.UnityHelpers.Utils; var options = new PoolOptions { // Size limits MaxPoolSize = 100, // Hard cap on pool size MinRetainCount = 0, // Absolute minimum to keep WarmRetainCount = 2, // Keep 2 when active // Timing IdleTimeoutSeconds = 300f, // 5 minutes before eligible PurgeIntervalSeconds = 60f, // Periodic check interval // Intelligent purging UseIntelligentPurging = true, BufferMultiplier = 2.0f, // 2x peak usage buffer RollingWindowSeconds = 300f, // 5 minute window HysteresisSeconds = 120f, // 2 minute spike cooldown SpikeThresholdMultiplier = 2.5f, // 2.5x average = spike MaxPurgesPerOperation = 10, // Spread large purges // Triggers Triggers = PurgeTrigger.OnRent | PurgeTrigger.OnReturn, // Callbacks OnPurge = (item, reason) => Debug.Log($"Purged: {reason}") }; var pool = new WallstopGenericPool( createFunc: () => new MyObject(), options: options ); ``` -------------------------------- ### Set Z.AI API key in .env.local Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Mcp-Local-Setup Add the Z.AI API key to the gitignored .env.local file before opening the devcontainer. The key is resolved only when a Z.AI server starts and is never copied into MCP client configs or placed on a process command line. If absent, the launcher exits with a setup instruction. ```bash Z_AI_API_KEY= ``` -------------------------------- ### Boxed and typed field getters/setters for instance and static fields Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Reflection-Helpers Use the boxed overloads when the field type is only known at runtime, and the typed overloads to avoid boxing when types are known at compile time. Static fields use getters/setters that take no instance. The example shows setting and getting an instance field, and reading/writing a static field. ```csharp // Boxed: works for any field, returns/accepts object. FieldInfo health = typeof(Enemy).GetField("health"); Func getHealth = ReflectionHelpers.GetFieldGetter(health); Action setHealth = ReflectionHelpers.GetFieldSetter(health); Enemy enemy = new(); setHealth(enemy, 25); Debug.Log((int)getHealth(enemy)); // 25 // Typed: no boxing. Func getHealthTyped = ReflectionHelpers.GetFieldGetter(health); int current = getHealthTyped(enemy); // Static fields get delegates that take no instance at all. FieldInfo currentSettings = typeof(GameSettings).GetField( "Current", BindingFlags.Public | BindingFlags.Static ); Func readSettings = ReflectionHelpers.GetStaticFieldGetter( currentSettings ); Action writeSettings = ReflectionHelpers.GetStaticFieldSetter( currentSettings ); ``` -------------------------------- ### AdminPrepare phase: install-windows-actions-runner.ps1 Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Runbooks-Unity-Runners-After-Transfer Run as administrator in Windows PowerShell 5.1 to prepare the service directory. Replace the account and machine name examples with actual values. ```powershell powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\unity\install-windows-actions-runner.ps1 ` -Phase AdminPrepare -InstallRoot C:\actions-runner -RunnerUser runner-owner ``` -------------------------------- ### StartTracker: Add component and check Started Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Utility-Components Add StartTracker to a GameObject and check its Started property to determine if Start() has been called. Useful for initialization order checking and editor tools. ```csharp using WallstopStudios.UnityHelpers.Utils; // Add to GameObject StartTracker tracker = gameObject.AddComponent(); // Later, check if Start has been called if (tracker.Started) { // Initialization complete } ``` -------------------------------- ### Inspector Display Examples Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Inspector-Validation-Attributes Examples of different WNotNull configurations and their inspector display. ```APIDOC ## Inspector Display Examples ### Description Examples of different WNotNull configurations and their inspector display. ### Example ```csharp using UnityEngine; using WallstopStudios.UnityHelpers.Core.Attributes; public class EnemyAI : MonoBehaviour { // Yellow warning - nice to have [WNotNull] public ParticleSystem hitEffect; // Red error - critical reference [WNotNull(WNotNullMessageType.Error)] public Transform patrolPath; // Warning with helpful context [WNotNull("Assign the player tag or the enemy won't detect the player")] public string playerTag; // Error with specific instructions [WNotNull(WNotNullMessageType.Error, "Drag the NavMeshAgent component here - required for movement")] public UnityEngine.AI.NavMeshAgent agent; } ``` ``` -------------------------------- ### Beginner Example: PlayerController with Inject and Relational Attributes Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/Samples~/DI - Reflex/README.md Shows a MonoBehaviour using [Inject] for services and [SiblingComponent]/[ChildComponent] for hierarchy references. Requires enabling 'Assign Scene On Initialize' in RelationalComponentsInstaller for automatic scene wiring. ```csharp public class PlayerController : MonoBehaviour { // Injected dependencies [Inject] private IInputService _input; [Inject] private IAudioService _audio; // Hierarchy references (auto-wired) [SiblingComponent] private Animator _animator; [SiblingComponent] private Rigidbody2D _rigidbody; [ChildComponent(TagFilter = "Weapon")] private Weapon _weapon; // Everything wired automatically when scene loads! void Update() { Vector2 input = _input.GetMovementInput(); _rigidbody.velocity = input * moveSpeed; _animator.SetFloat("Speed", input.magnitude); } } ``` -------------------------------- ### Verify PowerShell 7 installation Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Runbooks-Unity-Runners-After-Transfer Run these commands in a new shell to confirm PowerShell 7 is installed and accessible. 'pwsh -v' prints the installed version, and 'Get-Command pwsh' resolves to the executable's path. ```powershell pwsh -v Get-Command pwsh ``` -------------------------------- ### colorKey parameter examples Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Inspector-Button Shows how to apply custom color themes to buttons using predefined color keys like "Danger", "Success", and "Warning". ```csharp // Default blue button [WButton("Standard Action")] private void StandardAction() { } // Custom themed button (requires setup in project settings) [WButton("Dangerous Action", colorKey: "Danger")] private void DangerousAction() { } [WButton("Success Action", colorKey: "Success")] private void SuccessAction() { } [WButton("Warning Action", colorKey: "Warning")] private void WarningAction() { } ``` -------------------------------- ### Offset scaling example Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Inspector-Utility-Components Text example showing how the CenterPoint is calculated by multiplying the offset by the transform's local scale. ```text transform.position = (0, 0) offset = (1, 0) transform.localScale = (2, 2, 2) CenterPoint = (0, 0) + (1, 0) * (2, 2) = (2, 0) ``` -------------------------------- ### Install npm dependencies Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Project-Contributing Install npm dependencies without audit or funding. The generated root lockfile stays ignored. ```bash npm install --no-audit --no-fund ``` -------------------------------- ### VContainer: Manual Entry Point Initialization for Tests Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Relational-Components-Relational-Components Construct the entry point and call Initialize() yourself when not using LifetimeScope. Register an AttributeMetadataCache instance so the assigner uses it. Lookups rebuild on first use after metadata changes. ```csharp var cache = ScriptableObject.CreateInstance(); // Populate metadata with cache.SetMetadata(...) in the editor. // Lookups rebuild on first use after metadata changes. var builder = new ContainerBuilder(); builder.RegisterInstance(cache).AsSelf(); builder.Register(Lifetime.Singleton) .As() .AsSelf(); var resolver = builder.Build(); var entry = new RelationalComponentEntryPoint( resolver.Resolve(), cache, RelationalSceneAssignmentOptions.Default ); entry.Initialize(); ``` -------------------------------- ### EffectHandler Effect State Queries Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Effects-Effects-System Check if an effect is active, get its stack count, and get remaining duration for an effect instance. ```csharp // Check if a specific effect is currently active if (effectHandler.IsEffectActive(hasteEffect)) { ShowHasteIndicator(); } // Get the stack count for an effect int hasteStacks = effectHandler.GetEffectStackCount(hasteEffect); Debug.Log($"Haste stacks: {hasteStacks}"); // Get remaining duration for a specific effect instance if (effectHandler.TryGetRemainingDuration(effectHandle, out float remaining)) { UpdateDurationUI(remaining); } ``` -------------------------------- ### Reflex prefab instantiation with DI and relations Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/docs/readme.md Shows how to instantiate a prefab with DI and relations using Reflex's container.InstantiateComponentWithRelations(). ```csharp // Reflex: prefab instantiation with DI + relations using Reflex.Core; using WallstopStudios.UnityHelpers.Integrations.Reflex; var enemy = container.InstantiateComponentWithRelations(enemyPrefab, parent); ``` -------------------------------- ### CoroutineHandler.Instance.StartCoroutine(IEnumerator) Source: https://github.com/ambiguous-interactive/unity-helpers/blob/main/docs/features/inspector/utility-components.md Starts a coroutine on the global CoroutineHandler singleton. This allows coroutines to be started from static classes, plain C# objects, and ScriptableObjects. ```APIDOC ## CoroutineHandler.Instance.StartCoroutine(IEnumerator) ### Description Starts a coroutine on the global CoroutineHandler singleton. This allows coroutines to be started from static classes, plain C# objects, and ScriptableObjects. ### Method StartCoroutine ### Endpoint CoroutineHandler.Instance.StartCoroutine(IEnumerator) ### Parameters #### Method Parameters - **routine** (IEnumerator) - Required - The coroutine to start. ### Request Example ```csharp CoroutineHandler.Instance.StartCoroutine(MyCoroutine()); ``` ### Response #### Success Response - **Coroutine** - The started coroutine, which can be used to stop it later. #### Response Example ```csharp Coroutine routine = CoroutineHandler.Instance.StartCoroutine(MyCoroutine()); ``` ``` -------------------------------- ### Create a ScriptableObjectSingleton settings asset with custom path Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Features-Utilities-Singletons Defines a settings asset that inherits from ScriptableObjectSingleton and uses the [ScriptableSingletonPath] attribute to place it under Resources/Settings/Audio. Access the singleton via T.Instance, which lazy-loads the asset from Resources and warns if multiple assets are found. ```csharp using WallstopStudios.UnityHelpers.Utils; using WallstopStudios.UnityHelpers.Core.Attributes; [ScriptableSingletonPath("Settings/Audio")] public sealed class AudioSettings : ScriptableObjectSingleton { public float musicVolume = 0.8f; public bool enableSpatialAudio = true; } // Usage at runtime float vol = AudioSettings.Instance.musicVolume; ``` -------------------------------- ### Install PowerShell 7 with winget Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Runbooks-Unity-Runners-After-Transfer Use this command on a machine with winget to install PowerShell 7. The package ID is Microsoft.PowerShell and the source is winget. ```powershell winget install --id Microsoft.PowerShell --source winget ``` -------------------------------- ### TryApply Source: https://github.com/ambiguous-interactive/unity-helpers/wiki/Guides-Odin-Migration-Guide Applies the preview's captured source bytes using the same transaction as the menu tool. A successful preview can be applied once. ```APIDOC ## TryApply ### Description Applies the preview's captured source bytes using the same transaction as the menu tool. A successful preview can be applied once. ### Method TryApply ### Parameters - **preview** (Preview) - Required - The preview to apply. - **out backupRoot** (string) - Required - The backup root location. - **out failure** (Failure) - Required - Details of any failure. ### Response - **bool** - True if apply succeeded; false on failure. ```