Skip to content

Features Utilities Helper Utilities

github-actions[bot] edited this page Nov 15, 2026 · 73 revisions

Helper Utilities Guide

TL;DR: Why Use These

Static helper classes and utilities that solve common programming problems without needing components on GameObjects. Use these for predictive aiming, path utilities, threading, hashing, formatting, and more.


Contents


Editor Asset Helpers

Use Helpers.EnumerateAssets<T>(folders) in editor code to read matching main assets and subassets, including animation clips embedded in another asset. T can be any UnityEngine.Object type. Omitting folders searches Assets; an empty folder collection returns no results. Enumeration loads assets and runs on the Editor main thread. The existing ScriptableObject and prefab helpers keep their existing search defaults.

Use Helpers.CreateOrReplaceAsset(source, path) to save a generated native asset without breaking references to a previous version. It returns the saved object, which is the existing object during replacement, or null on failure. TryCreateOrReplaceAsset also returns an error message. Always use the returned object for subsequent edits: replacement copies source contents into the destination; it does not turn a temporary source into that persistent object.

The destination must be below Assets in an existing folder. Replacement requires a native main asset of the same concrete type. Imported files such as PNGs, subasset sources, type changes, scenes, prefabs, components, sources marked DontSaveInEditor, missing folders, and relative path traversal are refused. Supported native extensions are .asset, .anim, .mat, .guiskin, .cubemap, .mask, .physicMaterial, .physicsMaterial2D, .renderTexture, .controller, .overrideController, .terrainlayer, and .flare. A persistent source can supply replacement contents, but cannot be moved to a new path through this helper.

Replacement keeps the destination GUID and local file ID. Copying a distinct source records in-memory Undo. When saving an object you already edited, record Undo before your edit. File creation, saving and reimporting cannot be fully reversed with Undo. A failed save can leave an unsaved in-memory change; inspect the error and destination before retrying. A save that leaves the asset dirty, including a write blocked by OnWillSaveAssets, reports failure before reimporting. Native write errors for the destination are also observed during saving, because Unity can clear its dirty flag after an unsuccessful write. The requested in-memory edit stays available for retry. This API does not coordinate with external writers and never deletes a destination as failure cleanup. Saving uses AssetDatabase.SaveAssets, which also flushes other dirty project assets.

Live Component Registries

Use LiveComponents<T> from WallstopStudios.UnityHelpers.Utils to select a component class, base class or interface. Queries discover matching components automatically, including third-party scripts and native components. Existing objects, subclasses and interface implementations need no adapter, attribute, registration call or lifecycle change.

using UnityEngine;
using WallstopStudios.UnityHelpers.Utils;

public sealed class RegisteredLevelStatus : MonoBehaviour
{
    public bool started;

    public static bool IsLevelStarted()
    {
        return LiveComponents<RegisteredLevelStatus>.TryGetFirst(out RegisteredLevelStatus level)
            && level.started;
    }
}
Operation Behavior
Count Reconcile scenes and count all active matches.
TryGetFirst(out found) Return the first active cached match; reconcile on a miss.
TryGetIn(scene, out found) Return the first active match in the object's current scene; reconcile on a miss.
CopyTo(destination) Reconcile and replace a reusable list with all active matches. Null is ignored.

Results retain first-discovery order. Initial discovery order is unspecified. Inactive GameObjects, disabled Behaviour components and destroyed objects are excluded. Enabling, adding, instantiating, and moving components take effect in subsequent queries, even within the same frame. A cached first match remains first when later components are discovered. No negative result is cached across calls. Counts and complete copies always reconcile to include new instances.

Only queried types retain entries. Per-type lists and identity sets are reused. A valid cached first match avoids scene traversal. Reconciliation visits loaded scene roots and collects only components assignable to T; its cost grows with the loaded hierarchy. This is a completeness tradeoff, not a constant-time replacement for every scene search. Initial discovery and queries during scene loading also use Unity's object search and can allocate. Stable warmed queries allocate no managed memory when internal buffers and the caller's list have enough capacity.

The registry includes the DontDestroyOnLoad scene. It creates one hidden, scriptless persistent GameObject to access that scene through supported Unity APIs; this internal object is excluded from results. Subsystem registration clears type caches. The next query discovers surviving objects again, including when domain or scene reload is disabled. Existing component callbacks are untouched.

All operations require Unity's initialized main thread. Worker calls return empty results or false; CopyTo leaves its destination untouched on a worker. In Edit Mode, queries visit loaded scenes. During Play Mode, results exclude objects belonging only to an editor or prefab world. A class that is neither a component class nor an interface produces empty results.

Coroutine Wait Pools

Unity allocates a new WaitForSeconds/WaitForSecondsRealtime every time you yield with a literal. Buffers.GetWaitForSeconds(...) and Buffers.GetWaitForSecondsRealTime(...) pool those instructions to reduce coroutine allocations, but each distinct duration used to stick around forever. Large ranges (randomized cooldowns, tweens, etc.) could leak thousands of instances.

Constant, computed, and random finite durations are supported. With the default settings, the cache uses the exact float value and retains at most 512 distinct durations; further values allocate a valid instruction without adding an entry. Optional quantization rounds both cached instructions and uncached fallbacks to the same duration. If quantization arithmetic would overflow, the original finite duration is preserved. A zero cache limit explicitly enables unbounded caching.

float delaySeconds = random.NextFloatInRange(minimumDelay, maximumDelay);
yield return Buffers.GetWaitForSeconds(delaySeconds);

New pooling policy knobs (Runtime 2.2.1+):

Setting Default Purpose
Buffers.WaitInstructionMaxDistinctEntries 512 Upper bound on distinct cached durations. Set to 0 to disable the cap, or tighten it for editor/dev builds. When the limit is reached the cache stops growing (or evicts, if LRU is enabled).
Buffers.WaitInstructionQuantizationStepSeconds 0 (off) Rounds requested durations to the nearest step before caching. Useful when you can tolerate millisecond snapping (e.g., .005f → .01f).
Buffers.WaitInstructionUseLruEviction false When true, the cache becomes an LRU: it evicts the least recently used duration whenever it hits the max entry count instead of rejecting new ones. Diagnostics expose the eviction count.
Buffers.TryGetWaitForSecondsPooled(float seconds) / TryGetWaitForSecondsRealtimePooled n/a Returns the cached instruction or null if the request would exceed the cap. Use this when you want to detect “unsafe” usages and allocate manually instead.
Buffers.WaitForSecondsCacheDiagnostics / .WaitForSecondsRealtimeCacheDiagnostics snapshot Exposes DistinctEntries, MaxDistinctEntries, LimitRefusals, and whether quantization is active so you can surface metrics in your own tooling.

⚙️ Project-wide defaults: Open the Coroutine Wait Instruction Buffers foldout under Project Settings ▸ Wallstop Studios ▸ Unity Helpers to edit these knobs. The settings asset lives at Resources/Wallstop Studios/Unity Helpers/UnityHelpersBufferSettings.asset, ships with your build, and automatically applies on script/domain reload or when a player starts (unless your code overrides the values at runtime). Use Apply Defaults Now to push the current sliders into the active domain or Capture Current Values to snapshot whatever Buffers is using in play mode.

🔒 Persistence Behavior: When you click Apply Defaults Now, the settings are immediately:

  1. Saved to disk: The asset is marked dirty and saved via AssetDatabase.SaveAssets()
  2. Applied to the runtime: Buffers.WaitInstruction* properties are updated immediately

This ensures settings persist across:

  • Domain reloads (script recompilation, entering/exiting play mode): Via [InitializeOnLoadMethod]
  • Editor restarts: The asset is saved to disk and reloads automatically
  • Standalone builds: The asset ships under Resources/ and auto-applies via [RuntimeInitializeOnLoadMethod]

Toggle Apply On Load to control whether the saved defaults auto-apply when the domain loads. If disabled, the asset serves as a reference and you must call asset.ApplyToBuffers() manually.

// Clamp the cache to 128 distinct waits, quantize to milliseconds, and reuse LRU entries.
Buffers.WaitInstructionMaxDistinctEntries = 128;
Buffers.WaitInstructionQuantizationStepSeconds = 0.001f;
Buffers.WaitInstructionUseLruEviction = true;

IEnumerator WeaponCooldown(Func<float> cooldownSeconds)
{
    float waitSeconds = cooldownSeconds();

    // Prefer pooled waits, but fall back to a fresh instance if the cache refuses it.
    WaitForSeconds pooled = Buffers.TryGetWaitForSecondsPooled(waitSeconds)
        ?? new WaitForSeconds(waitSeconds);

    yield return pooled;
}

void OnGUI()
{
    WaitInstructionCacheDiagnostics stats = Buffers.WaitForSecondsCacheDiagnostics;
    GUILayout.Label(
        $"Wait cache: {stats.DistinctEntries}/{stats.MaxDistinctEntries} (refusals={stats.LimitRefusals}, evictions={stats.Evictions})"
    );
}

⚠️ Limit warnings: In Editor and Development builds the first limit hit (and every 25th after) emits a warning so you can spot misuses quickly. Production builds skip the log to avoid noise.

✅ Deterministic fallback: When the cache refuses a duration, Buffers.GetWaitForSeconds* still returns a valid instruction; it just isn’t cached, so highly variable waits no longer lead to unbounded memory growth.


Pooling Unity Objects That Outlive Their Scope

TrackedObjectPool<T> pools UnityEngine.Object instances whose lifetime ends in a callback rather than at the end of a scope (a tween's OnComplete, an animation event, a coroutine).

That is the one shape WallstopGenericPool<T> cannot serve. It hands out a PooledResource<T> whose disposal returns the item, which is a lexical scope and therefore cannot strand anything; it also cannot refuse a return, and refusing one is the point here. Use it for scratch buffers, and this for pooled effects.

TrackedObjectPool<GameObject> puffs = new(
    producer: () => Instantiate(_puffPrefab),
    onTake: puff => puff.SetActive(true),
    onRelease: puff => puff.SetActive(false),
    onDestroy: puff => Destroy(puff));

if (puffs.TryTake(out GameObject puff))
{
    puff.transform.position = point;
    tween.OnComplete(() => puffs.Release(puff));
}

// Destroys the puff still in flight too, rather than leaving it in the scene.
puffs.Dispose();
Member What it answers
TryTake(out T) false when the pool is disposed or nothing could be produced. An item destroyed while pooled is discarded, never handed out.
Release(T) false for a double release, for something this pool never handed out, and for a release arriving after Dispose. It never throws: the caller is usually a completion callback, where a throw surfaces nowhere.
InFlightCount How many are checked out, and would be destroyed by a teardown right now.
Dispose() Applies onDestroy to everything, in flight included, draining the tracking list first so a Release from a destroyed item's own ending is refused rather than counted twice.

An item destroyed while checked out is still removed from tracking when released: ReferenceEquals(item, null) asks whether anything was handed in, item == null asks whether it is gone, and skipping the removal on the second question leaks one dead reference per use. The pool never calls Object.Destroy on its own initiative: onDestroy is where destruction lives, and a null one means something else owns it.

Callbacks can dispose the pool or destroy an item. TryTake returns false with a null output when its callback disposes the pool, destroys the item, or releases it. A nested take after that release keeps its own ownership. A release callback that disposes the pool retires the returned item through onDestroy instead of retaining it.

Callback exceptions are logged. A failed producer returns no item; it remains responsible for resources it never returns. A failed take retires its live item through onDestroy while that take still owns it. A failed release callback retires its live item. Release still returns true because it removed an item owned by this pool. If onDestroy throws, cleanup continues with the remaining items and clears all tracking. The caller must clean up any native object its destruction callback failed to destroy.


Pools by Key

KeyedObjectPool<TKey, T> owns a TrackedObjectPool<T> for each requested key. Its producer receives the key when a new object is needed; equivalent keys reuse the first key's pool. Release(item) finds the owner by managed object identity, including for destroyed objects. Foreign items, duplicate returns, null keys and post-disposal operations return false. A producer returning an object already owned by any of this owner's pools is refused.

Use it on the Unity main thread. Keys must keep stable equality and hashing. The optional maxIdleCount applies separately to each key; zero or less means unbounded. Dispose reaches both idle and checked-out live items through onDestroy. A null destruction callback leaves object destruction to the caller. Callback exceptions are logged and follow the tracked pool's failure rules; callbacks may release items or dispose the owner. Same-key recursive production is refused. Warm checkout and return of existing items allocate no garbage.

using UnityEngine;
using WallstopStudios.UnityHelpers.Utils;

using KeyedObjectPool<int, Texture2D> textures = new(
    producer: key => new Texture2D(key, key),
    onDestroy: texture => UnityEngine.Object.Destroy(texture));
if (textures.TryTake(16, out Texture2D texture))
{
    textures.Release(texture);
}

Gameplay Helpers

Predictive Aiming

What it does: Calculates where to aim when shooting at a moving target, accounting for projectile travel time.

Problem it solves: Shooting a bullet at where an enemy is misses if they're moving. You need to aim at where they will be.

using WallstopStudios.UnityHelpers.Core.Helper;

Vector2 enemyPos = enemy.transform.position;
Vector2 enemyVelocity = enemy.GetComponent<Rigidbody2D>().velocity;
Vector2 turretPos = turret.transform.position;
float bulletSpeed = 20f;

Vector2? aimPosition = Helpers.PredictCurrentTarget(
    enemyPos,
    enemyVelocity,
    turretPos,
    bulletSpeed
);

if (aimPosition.HasValue)
{
    // Aim at aimPosition to hit the moving target
    Vector2 aimDirection = (aimPosition.Value - turretPos).normalized;
    FireProjectile(aimDirection, bulletSpeed);
}
else
{
    // Target is too fast, can't hit
}

When to use:

  • Turrets shooting at moving enemies
  • AI aiming at moving players
  • Predictive targeting systems
  • Guided missiles

When NOT to use:

  • Homing projectiles (use steering behaviors)
  • Instant-hit weapons (use raycasts)
  • Slow-moving or stationary targets (just aim directly)

Spatial Sampling

Get random points in circles/spheres:

using WallstopStudios.UnityHelpers.Core.Helper;

// Random point inside circle (uniform distribution)
Vector2 spawnPoint = Helpers.GetRandomPointInCircle(center, radius);

// Random point inside sphere (uniform distribution)
Vector3 explosionPoint = Helpers.GetRandomPointInSphere(center, radius);

Use for:

  • Spawn points (enemies, pickups, particles)
  • Explosion damage distribution
  • Random movement destinations
  • Scatter patterns

Circular Curves and Arcs

ShapeHelper generates evenly spaced Vector2 points from angles expressed in degrees. Curve generation includes both requested endpoints; a one-point curve samples the angular midpoint.

using System.Collections.Generic;
using UnityEngine;
using WallstopStudios.UnityHelpers.Core.Helper;

List<Vector2> points = new(16);
ShapeHelper.GenerateCircularCurvePoints(
    center: Vector2.zero,
    radius: 4f,
    startAngle: 30f,
    endAngle: 150f,
    pointCount: 16,
    buffer: points
);

GenerateTopCircularFraction takes a fraction of the upper 180° semicircle and centers it on 90°. GenerateCircularFraction takes a fraction of a full 360° circle and centers it on a caller-supplied angle. A full-circle fraction includes geometrically identical first and last points, which is useful for an open polyline; omit the last point when feeding a renderer that already closes its loop.

Supplying a buffer clears and reuses that list. Invalid counts, radii, fractions, centers, or angles fail softly by returning an empty destination instead of throwing.


Smooth Rotation Helpers

Get rotation speed for smooth turning:

using WallstopStudios.UnityHelpers.Core.Helper;

// Calculate how much to rotate this frame toward target
float currentAngle = transform.eulerAngles.z;
float targetAngle = GetTargetAngle();
float maxDegreesPerSecond = 180f;

float newAngle = Helpers.GetAngleWithSpeed(
    currentAngle,
    targetAngle,
    maxDegreesPerSecond,
    Time.deltaTime
);

transform.eulerAngles = new Vector3(0, 0, newAngle);

Handles:

  • Frame-rate independence
  • Shortest rotation path (doesn't spin 270° when 90° is shorter)
  • Angle wrapping (0-360°)

Delayed Execution

Execute code after delay or next frame:

using WallstopStudios.UnityHelpers.Core.Helper;

// Execute after 2 seconds
Helpers.ExecuteFunctionAfterDelay(
    monoBehaviour,
    () => Debug.Log("Delayed!"),
    delayInSeconds: 2f
);

// Execute next frame
Helpers.ExecuteFunctionNextFrame(
    monoBehaviour,
    () => Debug.Log("Next frame!")
);

Uses coroutines under the hood.

Use TrackedDelayExtensions when an owner has several one-shot callbacks pending. Keep one List<Coroutine> per owner, schedule through ExecuteTrackedAfterDelay or TryExecuteTrackedAfterDelay, and call StopTrackedDelays from that owner's OnDisable or OnDestroy. A callback removes its handle before it runs, including when it throws or schedules more work. Nonpositive, NaN and infinite delays resume after scaled time advances, like a zero-second delay.

TryExecuteTrackedAfterDelay returns false for a missing owner, inactive GameObject, missing list or missing callback. ExecuteTrackedAfterDelay throws ArgumentNullException for a missing or destroyed owner, missing list or missing callback; an inactive GameObject schedules nothing. Stopping forgets the current handles before cancellation, so callbacks that schedule more work during cancellation retain their new handles. A destroyed owner still clears the list. These APIs run on Unity's main thread; stopping a coroutine through another API does not remove its tracked handle.


Repeating Execution with Jitter

Use owner.StartPeriodicJob(tick, updateRate) from WallstopStudios.UnityHelpers.Core.Extension to name each tick in the Unity Profiler. The marker is PeriodicJob.<context type>.<callback method>. Pass context when the work belongs to another object; the coroutine still stops with its host. A missing or destroyed host, or a missing callback, throws ArgumentNullException. An inactive GameObject returns null. A disabled behaviour on an active GameObject can host work, like an ordinary Unity coroutine.

StartFunctionAsCoroutine, ExecuteFunctionAfterDelay, ExecuteFunctionNextFrame and ExecuteFunctionAfterFrame use the same required-owner and required-action contract. Validate optional inputs before calling these methods, or use TryExecuteTrackedAfterDelay when scheduling may fail.

The first tick runs during startup unless waitBefore or useJitter delays it. Jobs use scaled time, run at most once per frame, and start each interval after the previous callback finishes. Late frames do not produce catch-up ticks. Nonpositive, NaN, and infinite intervals run once per frame. Startup allocates a coroutine and a callback wrapper. Scheduling and waits reuse that storage; callback allocations are separate. Callback failures are reported once and do not stop the job, even if exception formatting or the log handler fails. Keep the returned Coroutine to stop it early with owner.StopCoroutine(job).

Run a function repeatedly with an optional randomized initial delay:

using WallstopStudios.UnityHelpers.Core.Helper;

// Spawn every 5 seconds after a randomized initial delay
Helpers.StartFunctionAsCoroutine(
    gameManager,
    SpawnEnemy,
    updateRate: 5f,
    useJitter: true,
    waitBefore: false,
    context: waveController
);

void SpawnEnemy()
{
    Instantiate(enemyPrefab, spawnPoint.position, Quaternion.identity);
}

Pass context when the object that owns the work is not the MonoBehaviour that hosts the coroutine. The first callback failure is filed against that object in the Console. A null context uses the coroutine host.

Pass an exceptionHandler to program against failures instead of logging them. It receives every failed invocation's zero-based index, resolved context, and exception. The coroutine continues when the action or handler throws; a handler failure is logged once. If an exception cannot be formatted, the helper attempts one plain diagnostic. A failing custom log handler cannot stop the job. The same protection applies to ExecuteOverTime callbacks.

Helpers.StartFunctionAsCoroutine(
    CoroutineHandler.Instance,
    SaveGame,
    updateRate: 30f,
    useJitter: false,
    waitBefore: false,
    context: saveController,
    exceptionHandler: (iteration, owner, exception) =>
        Debug.LogError($"Save invocation {iteration} failed: {exception}", owner)
);

Use for:

  • Enemy spawning with variability
  • Random event triggers
  • Staggered updates to spread CPU load
  • Natural-feeling timing

updateRate values that are nonpositive, NaN or infinite use the once-per-frame behavior, including when initial jitter or waitBefore is enabled. Jitter is applied only before the first invocation.

For cached computations, TimedCache<T> requires a finite nonnegative lifetime and throws ArgumentException for a negative or nonfinite lifetime. Negative or nonfinite jitter overrides act as zero jitter. Zero lifetime supports jitter without requesting an empty random range; an explicit finite positive jitter override still delays the initial expiry. Expiry arithmetic preserves finite lifetimes and jitter when their sum would overflow a float. The supplied float clock expires the cache only when elapsed time exceeds the lifetime plus initial jitter. Small clock offsets and jitter remain significant beside very large lifetimes. A factory or time provider exception leaves the cached value, refresh timer, and initial jitter unchanged; retrying uses the original expiry schedule. A successful refresh consumes the initial jitter.


Layer & Label Queries

using WallstopStudios.UnityHelpers.Core.Helper;

// Get all layer names (cached after first call)
string[] allLayers = Helpers.GetAllLayerNames();

// Get all sprite label names (editor only, cached)
string[] labels = Helpers.GetAllSpriteLabelNames();

Use for:

  • Populating dropdowns in editor tools
  • Runtime layer/label validation
  • Configuration systems

Collider Syncing

Update PolygonCollider2D to match sprite:

using WallstopStudios.UnityHelpers.Core.Helper;

SpriteRenderer renderer = GetComponent<SpriteRenderer>();
PolygonCollider2D collider = GetComponent<PolygonCollider2D>();

Helpers.UpdateShapeToSprite(renderer, collider);
// Collider now matches sprite's physics shape

GameObject & Component Helpers

Cached Component Lookup

Tag-based component finding with caching:

using WallstopStudios.UnityHelpers.Core.Helper;

// First call searches scene, subsequent calls use cache
Player player = Helpers.Find<Player>("Player");

// Drop one tag's entry, if it still holds this instance
Helpers.ClearInstance("Player", player);

// Set cache manually (for dependency injection scenarios)
Helpers.SetInstance("Player", playerInstance);

// Drop every entry
Helpers.ClearTagCache();

Performance: First call searches the scene using GameObject.FindWithTag; subsequent calls use a cached O(1) dictionary lookup.

Lifetime: An entry holds a strong reference to the component it cached, so while the game is running, unloading a scene drops every entry whose object went with it. Anything that survives the unload stays cached. In the editor outside play mode nothing sweeps the cache; ClearTagCache() drops the lot either way.


Component Existence Checks

using WallstopStudios.UnityHelpers.Core.Helper;

// Check if component exists without allocating
bool hasRigidbody = Helpers.HasComponent<Rigidbody2D>(gameObject);

// Better than:
bool hasRigidbody = GetComponent<Rigidbody2D>() != null; // Allocates

Get-or-Add Pattern

using WallstopStudios.UnityHelpers.Core.Helper;

// Get existing component or add if missing
Rigidbody2D rb = Helpers.GetOrAddComponent<Rigidbody2D>(gameObject);

Hierarchical Enable/Disable

Recursively enable/disable components:

using WallstopStudios.UnityHelpers.Core.Helper;

// Enable all Collider2D components in children
Helpers.EnableRecursively<Collider2D>(rootObject, enable: true);

// Disable all renderers in hierarchy
Helpers.EnableRendererRecursively<SpriteRenderer>(rootObject, enable: false);

Use for:

  • Toggling collision for entire character rigs
  • Hiding/showing complex prefabs
  • Debug visualization toggles

Bulk Child Destruction

using WallstopStudios.UnityHelpers.Core.Helper;

// Destroy all children (useful for clearing containers)
Helpers.DestroyAllChildrenGameObjects(parentTransform);

Use for:

  • Clearing inventory UI
  • Resetting spawn containers
  • Cleanup before repopulating

Smart Destruction

Editor/runtime aware destruction:

using WallstopStudios.UnityHelpers.Core.Helper;

// Uses DestroyImmediate in editor, Destroy in play mode
Helpers.SmartDestroy(gameObject);

// Also handles assets correctly (won't destroy project assets)

Use in editor tools to avoid "Destroying assets is not permitted" errors.


Prefab Utilities

using WallstopStudios.UnityHelpers.Core.Helper;

// Check if GameObject is a prefab asset or instance
bool isPrefab = Helpers.IsPrefab(gameObject);

// Safely modify prefab (editor only)
#if UNITY_EDITOR
Helpers.ModifyAndSavePrefab(prefabAssetPath, prefab =>
{
    // Modify prefab here
    var component = prefab.AddComponent<MyComponent>();
    component.value = 42;
    // Changes saved automatically
});
#endif

Transform Helpers

Hierarchy Traversal (Depth-First)

Visit all children recursively:

using WallstopStudios.UnityHelpers.Core.Helper;

// Depth-first traversal (visits deepest children first)
Helpers.IterateOverAllChildrenRecursively<SpriteRenderer>(rootTransform, renderer =>
{
    renderer.color = Color.red;
});

// Buffered version (reduces allocations)
using (var buffer = Buffers<Transform>.List.Get())
{
    Helpers.IterateOverAllChildrenRecursively(rootTransform, buffer.Value);
    foreach (Transform child in buffer.Value)
    {
        // Process children
    }
}

Hierarchy Traversal (Breadth-First)

Visit by depth level:

using WallstopStudios.UnityHelpers.Core.Helper;

// Breadth-first traversal with depth limit
Helpers.IterateOverAllChildrenRecursivelyBreadthFirst(
    rootTransform,
    transform => Debug.Log(transform.name),
    maxDepth: 3  // Only visit 3 levels deep
);

Use for:

  • Finding immediate area (not entire tree)
  • Level-based operations
  • Performance-sensitive searches

Parent Traversal

Walk up the hierarchy:

using WallstopStudios.UnityHelpers.Core.Helper;

// Find component in parents
Helpers.IterateOverAllParentComponentsRecursively<Canvas>(transform, canvas =>
{
    Debug.Log($"Found canvas: {canvas.name}");
});

// Get all parents (no component filter)
using (var buffer = Buffers<Transform>.List.Get())
{
    Helpers.IterateOverAllParents(transform, buffer.Value);
    // buffer contains all parent transforms up to root
}

Use for:

  • Finding UI Canvas parents
  • Inheritance checking (is this under X?)
  • Walking to root of hierarchy

Direct Children/Parents

using WallstopStudios.UnityHelpers.Core.Helper;

// Get immediate children (non-recursive)
using (var buffer = Buffers<Transform>.List.Get())
{
    Helpers.IterateOverAllChildren(transform, buffer.Value);
    // Only direct children, no grandchildren
}

Threading

Per-thread context (ThreadAmbient<T>)

ThreadAmbient<T>.Current reads the current thread's scoped context. Push(value) returns a readonly struct scope that restores the previous value when disposed. Nested scopes restore in reverse order, and copied or repeatedly disposed scopes cannot overwrite a newer scope. Null and default are valid context values.

All callers using the same closed T share one context on each thread. Use distinct context types for independent channels. Values stay on their originating thread and do not flow across async continuations. An early or cross-thread disposal does nothing; it can be retried on the owning thread after its child scopes finish. Scope.IsCurrent reports only the current top scope.

Push and disposal use no locks or per-scope managed allocations. Each thread receives an atomic identity on its first push; later pushes use only thread-local state. Runtime thread/type initialization is separate from the warmed allocation contract. Exhausting the finite identity space returns an inactive scope. This complements RestorableGlobal<T> when workers need independent context rather than one shared value.

using WallstopStudios.UnityHelpers.Core.Threading;

using (ThreadAmbient<string>.Scope outer = ThreadAmbient<string>.Push("generation"))
{
    using (ThreadAmbient<string>.Scope inner = ThreadAmbient<string>.Push("solver"))
    {
        System.Console.WriteLine(ThreadAmbient<string>.Current);
    }
    System.Console.WriteLine(ThreadAmbient<string>.Current);
}

UnityMainThreadDispatcher

Execute code on Unity's main thread from background threads:

Problem it solves: Unity APIs can only be called from the main thread. Background Tasks/threads can't directly manipulate GameObjects. This marshals callbacks back to the main thread.

See the dedicated Unity Main Thread Dispatcher guide for details about auto-creation, queue limits, the AutoCreationScope helper, and instance cleanup through the public AutoCreationScope.Enabled(...) and Disabled(...) operations.

using WallstopStudios.UnityHelpers.Core.Helper;
using System.Threading.Tasks;

async Task LoadDataInBackground()
{
    // Background thread work
    await Task.Run(() =>
    {
        // Expensive computation
        var data = LoadFromDatabase();

        // Need to update UI - marshal back to main thread
        UnityMainThreadDispatcher.Instance.RunOnMainThread(() =>
        {
            // Safe to call Unity APIs here
            uiText.text = data.ToString();
        });
    });
}

Async version with result:

async Task<string> 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;
}

SingleThreadedThreadPool

Supply onException to handle work failures on the worker without polling its exception queue:

using SingleThreadedThreadPool pool = new(
    runInBackground: true,
    noWorkWaitTime: null,
    onException: error => Console.Error.WriteLine(error)
);

A successful callback handles the error without retaining it in Exceptions. If the callback throws, the queue keeps both failures in an AggregateException, bounded to the latest 64 callback failures, and the worker continues. A null callback preserves the original queue behavior. The callback runs on the worker; it must return before that worker can finish draining or disposing.

Run background work one item at a time, in enqueue order:

The optional noWorkWaitTime controls how long an idle worker waits for a signal. Invalid delays use the default one-second interval, so a mistaken negative or oversized timeout cannot stop the worker and strand later save jobs. Valid delays retain SemaphoreSlim's integer-millisecond truncation, including fractional values, zero, and Timeout.InfiniteTimeSpan. Enqueueing still signals the worker immediately, even with an infinite idle delay.

Use TryEnqueue when the caller must know whether submission succeeded. Its Action, Func<Task>, and Func<ValueTask> overloads return false for a null delegate or a pool already closed by draining or disposal. Admission is checked atomically with queue insertion; checking IsAcceptingWork before Enqueue cannot provide that guarantee. Existing Enqueue overloads ignore null or rejected work.

if (!pool.TryEnqueue(() => SaveSnapshot(snapshot)))
{
    SaveSnapshot(snapshot);
}

A true result means the work entered the queue. It does not promise successful execution or protect it from later disposal. Stop producers and drain the pool when accepted save work must run.

Disposal discards queued work. Dispose() and DisposeAsync() cancel the worker rather than draining it, so anything enqueued but not yet started is dropped; the await inside DisposeAsync() waits only for the item already in flight. Disposal immediately removes pending work and releases the queue's references to its delegates; concurrent submissions cannot leave new work in a shut-down queue. Concurrent disposal calls all wait for the same in-flight item and handle cleanup, so none returns while shutdown is still running. Count reaches zero once the in-flight item finishes. That is what you want for work that can simply be redone, such as a generation pass, and not what you want for durable work such as a persistence write.

The window is narrow enough to hide in testing: work enqueued a millisecond or more before disposal almost always completes, work enqueued immediately before it almost never does.

Call DrainAsync() when queued items must run. It closes the pool to new work permanently, then returns once the queue is empty and nothing is executing. If disposal interrupts the drain, DrainAsync() returns false even when disposal emptied the pending queue:

using WallstopStudios.UnityHelpers.Core.Threading;

// Work that can be redone: drop whatever is still queued.
_generationPool.Dispose();

// Durable work: let the queue run down first.
if (!await _persistencePool.DrainAsync())
{
    this.Log()?.Warn("Pool did not drain; writing final state on this thread.");
}

await _persistencePool.DisposeAsync();

DrainAsync() returns false when the wait was abandoned via its CancellationToken, the pool was already disposed, or the worker had already stopped with items still queued, so a caller can fall back to writing the final state itself. IsAcceptingWork reports whether Enqueue still does anything.

The guarantee covers every item the calling thread enqueued before the call. A producer racing the drain from another thread is not covered, so stop those producers first.

One caveat on the synchronous Dispose(): it blocks the calling thread until the in-flight item finishes. The pool posts nothing back to Unity's main thread, so this is safe for ordinary work items. A work item whose own continuations capture the main thread's synchronization context would deadlock, because OnDestroy runs on that thread; prefer DisposeAsync() there. A work item can initiate DisposeAsync() and then return, but it must not await its own shutdown or call Dispose() because shutdown waits for that item to finish.

Semaphore Leases

SemaphoreSlim makes you pair every wait with a finally. Acquire() returns a SemaphoreLease instead, so the critical section is a using block:

using WallstopStudios.UnityHelpers.Core.Threading;

private readonly SemaphoreSlim _gate = new SemaphoreSlim(1, 1);

public void Append(string line)
{
    using (_gate.Acquire())
    {
        _lines.Add(line);
    }
}

public async Task AppendAsync(string line, CancellationToken cancellationToken)
{
    using (await _gate.AcquireAsync(cancellationToken))
    {
        _lines.Add(line);
    }
}

When you would rather not block, TryAcquire reports failure instead:

if (_gate.TryAcquire(TimeSpan.FromMilliseconds(50), out SemaphoreLease lease))
{
    using (lease)
    {
        // Took a permit within the timeout.
    }
}

SemaphoreLease is a struct, so an uncontended acquire allocates nothing. Its shared disposal slots are recycled when a lease is disposed on another thread, including after an await that resumes on a worker thread. Ownership tracking remains thread-safe with SINGLE_THREADED defined, including concurrent leases from independent semaphores and disposal through copies on different threads.

Disposal is tracked and idempotent. Disposing a lease twice returns one permit, not two. Without an explicit maximum, a stray Release() can raise the permit count above the intended limit and let two callers into a section built for one. IsHeld reports whether a lease still owns a permit, and a lease from a failed TryAcquire is not held, so disposing it is a no-op.

Copying a lease is safe. Assigning it to another variable, capturing it, or passing it by value produces copies that all point at the same permit, and exactly one of them releases it — whichever is disposed first. The claim is held outside the struct, where every copy reads the same state, so IsHeld reports false on every copy once any of them has released.

Construct semaphores with an explicit maximum. Copying is safe through the lease's shared claim. The maximum determines what happens when another caller releases a permit while a lease is held:

Constructor Another caller releases while a lease is held
new SemaphoreSlim(1, 1) A stray release raises SemaphoreFullException when the lease is disposed. Count survives.
new SemaphoreSlim(1) Maximum defaults to int.MaxValue, so the lease's release succeeds; the count rises to 2 and a second caller can enter the section.

Disposing a lease after its semaphore has been disposed is safe. A full semaphore during lease disposal indicates another caller released a permit it did not own; that error is allowed to throw.

Acquire directly into a using and let the lease dispose there. Do not call Release() separately for a permit held by a lease.

Acquire() and AcquireAsync() throw ArgumentNullException on a null semaphore rather than handing back a lease that is not held: a silently unlocked critical section surfaces far from its cause. TryAcquire reports false instead.


Logging

Use the Logging Extensions guide for:

  • Rich text tags applied directly inside interpolated strings ($"{value:b,color=red}")
  • Thread-aware logging helpers (this.Log, this.LogWarn, this.LogError, this.LogDebug)
  • Tips for registering custom decorations and gating logs per-object or globally

These helpers rely on the same dispatcher utilities above, so logging from jobs/background threads stays safe.

Fire-and-forget on main thread:

// From background thread
UnityMainThreadDispatcher.Instance.RunOnMainThread(() =>
{
    Instantiate(prefab, position, rotation);
});

When to use:

  • Async file loading callbacks
  • Network request callbacks
  • Database query results
  • Background computation results that update UI

Important:

  • Works in both edit mode and play mode
  • Actions queued during edit mode execute in next editor update
  • Don't block the main thread with long operations

Path & File Helpers

Path Sanitization

Normalize path separators:

using WallstopStudios.UnityHelpers.Core.Helper;

string windowsPath = @"Assets\Sprites\Player.png";
string unityPath = PathHelper.Sanitize(windowsPath);
// Result: "Assets/Sprites/Player.png"

Unity prefers forward slashes. Use this for cross-platform paths.


Directory Utilities

DirectoryHelper.ResolvePackageAssetPath returns an AssetDatabase path for package-relative content, including local packages referenced from an external checkout. Assets installations retain their Assets/ path; embedded, cached and external packages use Packages/<package-id>/. An external checkout with a missing or whitespace-only package identifier returns an empty path. FindAbsolutePathToDirectory uses the same resolver for directories in this package.

Create directories safely:

using WallstopStudios.UnityHelpers.Core.Helper;

#if UNITY_EDITOR
// Creates directory and updates AssetDatabase
DirectoryHelper.EnsureDirectoryExists("Assets/Generated/Data");
#endif

In the Editor, directory creation canonicalizes paths before touching disk or the AssetDatabase. Assets/Generated/Discarded/../Data creates Assets/Generated/Data; discarded folders are not created. Mixed separators and any casing of the initial Assets segment are supported. Invalid paths and paths resolving outside Assets, such as Assets/../Temp/Data, raise ArgumentException without writing outside Assets. Blank inputs remain a no-op. Existing disk-only directories are imported without creating numbered duplicates.

AssetDatabaseBatchHelper.EnsureAssetFolder and EnsureAssetParentFolder apply the same normalization and return false for invalid or escaping paths. Singleton failure cleanup also refuses escaping paths before deleting assets or disk files. These checks provide lexical containment; symbolic links within Assets are not resolved, so physical containment is not guaranteed. Player builds retain the ordinary Directory.CreateDirectory behavior.

Find package root:

// Walk hierarchy to find package.json
string packageRoot = DirectoryHelper.FindPackageRootPath();
// Returns path to package containing calling script

Use for:

  • Editor tools generating assets
  • Finding package-relative paths
  • Build scripts creating folders

Path Conversion

Convert between absolute and Unity-relative paths:

using WallstopStudios.UnityHelpers.Core.Helper;

string absolute = "C:/Projects/MyGame/Assets/Textures/player.png";
string relative = DirectoryHelper.AbsoluteToUnityRelativePath(absolute);
// Result: "Assets/Textures/player.png"

For paths in Library/PackageCache, DirectoryHelper.AbsoluteToUnityLoadablePath needs the package ID to build a Packages/<package-id>/ path. It returns an empty string when the package ID is blank, so callers can skip a path that Unity cannot load.

Get calling script's directory:

// Uses [CallerFilePath] magic
string scriptDir = DirectoryHelper.GetCallerScriptDirectory();
// Returns directory containing the calling .cs file

File Operations

Initialize file if missing:

using System.Text;
using WallstopStudios.UnityHelpers.Core.Helper;

// Create config.json with default contents if it doesn't exist
FileHelper.InitializePath(
    "Assets/config.json",
    Encoding.UTF8.GetBytes("{ \"version\": 1 }")
);

InitializePath stages and flushes initial contents before publishing them at a free path. A failed write leaves the destination absent, so you can retry without deleting a partial save. It returns false for an existing file or directory, a blank path, an I/O failure, or a platform or filesystem that cannot publish a complete file atomically while preserving a competing creator. Null contents create an empty file. Missing parent directories are created. Paths containing spaces and legal long filenames remain supported.

Operations through DurableFile and FileHelper serialize on the same path within this process. Publication preserves a file created by another process before publication; it does not prevent another process from replacing the file afterward. Temporary files use short random names in the same directory and are removed on a best-effort basis. An interrupted process can leave one behind.

Async file copy:

A zero or negative copy buffer returns false before opening files. The destination keeps its previous contents if reading or staging fails, or if the copy is cancelled. A successful copy replaces it after the full source has been staged. On platforms that do not support file replacement, the final swap deletes the old destination before moving the staged file; a failed move can leave the destination absent. A temporary sibling file may remain after an interrupted process.

using System.Threading;

CancellationTokenSource cts = new CancellationTokenSource();

await FileHelper.CopyFileAsync(
    "source.txt",
    "destination.txt",
    bufferSize: 81920,  // 80KB buffer
    cts.Token
);

Use for:

  • Large file operations without blocking
  • Cancellable copy operations
  • Streaming file operations

Durable Writes for Player Data

File.WriteAllText empties the destination before it writes a single byte. If the game is killed, the device loses power, or the disk fills in between, the player's save is gone and a truncated one is in its place. DurableFile writes the new contents to a sibling file, forces them to disk, and only then swaps them over the destination.

using WallstopStudios.UnityHelpers.Core.Helper;

if (!DurableFile.TryWriteAllText(savePath, json, out Exception error))
{
    Debug.LogError($"Could not save: {error}");
    // A failed staging write leaves the previous save intact.
}

The text overload writes UTF-8 without a byte order mark by default. Pass an Encoding when the file format requires its preamble; TryWriteAllText(path, text, Encoding.UTF8, out error) writes the UTF-8 byte order mark before the text.

For binary saves, TryWriteAllBytes and WriteAllBytesAsync accept the serialized byte[] directly. They use the same staging and flush guarantees as text writes, without encoding or copying the payload. Missing directories are created; null or empty bytes replace the destination with an empty file. Keep the array unchanged until the call completes.

if (!DurableFile.TryWriteAllBytes(savePath, serializedBytes, out Exception error))
{
    Debug.LogError($"Could not save binary data: {error}");
}

Every method reports failure instead of throwing, and the async ones return the exception (null on success):

Exception error = await DurableFile.WriteAllTextAsync(savePath, json, cancellationToken);
Exception binaryError = await DurableFile.WriteAllBytesAsync(savePath, serializedBytes, cancellationToken);

// Append is stronger still: it never rewrites bytes that are already on disk.
DurableFile.TryAppendAllText(ledgerPath, $"{score}\n", out Exception appendError);

// Replace one file with another under the same staging discipline.
DurableFile.TryCopy(savePath, backupPath, out Exception copyError);

Serializer.WriteToJsonFile and WriteToJsonFileAsync already write through this, so JSON saves get the guarantee without changing any code.

Async whole-file writes and copies check cancellation again after staging and immediately before publication. Cancellation observed there returns a failure, preserves the previous destination (or its absence), attempts to remove the staged file, and releases ownership for a retry. Staged-file cleanup is best effort: a deletion failure can leave that temporary file behind. Cancellation arriving after that final check can still publish the complete new file. Appending records has a separate contract: a cancelled append may have written part of its new record.

What it promises:

  • On platforms with File.Replace, a reader sees either complete old or complete new contents.
  • Unsupported File.Replace reports failure and preserves the existing destination. Creating an absent destination still uses a move; subsequent replacements require platform support.
  • The data is forced out of the page cache before the swap makes it live.
  • Concurrent writes to the same path from your game are serialized.
  • Windows sharing violations and replacement error 1175 receive up to three replacement attempts with 10 ms and 20 ms waits. The staged bytes and ownership remain held through these attempts. Persistent contention reports failure and preserves the previous save. Other replacement failures propagate immediately.
  • A second process using the public DurableFile write, append, or delete APIs cannot change the same destination while the first operation owns it. Its competing operation reports failure.

What it does not promise:

  • It is not full crash safety. .NET cannot flush a directory, so a filesystem may still reorder the rename behind the data write.
  • The ownership applies to one destination at a time. It is not a transaction across several files.
  • Tools that do not use DurableFile do not share this ownership and can still edit a destination.
  • An internal compare-then-replace operation checks a file before staging its replacement, but unrelated writers can edit the destination between that check and the swap. It does not provide atomic content compare-and-swap against external tools. See #863 for the stronger contract under investigation. Tests reproduce a direct edit after comparison for both text and byte replacement: the complete staged replacement wins, so the external edit is lost. Use a shared writer protocol or a transactional store when that loss is unacceptable.

A leftover .tmp sibling (DurableFile.TemporarySuffix) is what an interrupted write leaves behind; it is safe to ignore or delete. DurableFile.TryDelete succeeds when a file is absent and reports failure for a directory or a file it cannot delete.

Coalesce Repeated Saves

Keep one LatestWriteFile for a store whose newest pending snapshot replaces earlier ones. It retains one queued payload per normalized path. A write already in progress finishes first; its newer replacement follows it. Text stays immutable and is encoded as UTF-8 only when written. Byte submissions make an owned copy so callers can immediately reuse their array. Path identity ignores case on Windows and macOS and uses ordinal comparison on other hosts.

using System;
using System.IO;
using WallstopStudios.UnityHelpers.Core.Helper;

string savePath = Path.Combine(Path.GetTempPath(), "player-save.json");
using LatestWriteFile writer = new(
    writeInBackground: false,
    onFailure: (path, failure) => Console.Error.WriteLine($"{path}: {failure}")
);

if (!writer.TryEnqueueText(savePath, "{\"score\":10}", out Exception submissionError))
{
    Console.Error.WriteLine(submissionError);
}
if (!writer.TryEnqueueText(savePath, "{\"score\":20}", out submissionError))
{
    Console.Error.WriteLine(submissionError);
}
if (!writer.Flush(out Exception writeError))
{
    Console.Error.WriteLine(writeError);
}

A successful submission means accepted, not saved. The default processes writes in the background; writeInBackground: false batches until an explicit Flush or disposal. In SINGLE_THREADED builds, automatic processing runs synchronously instead. PendingPathCount excludes the batch already being written. The example explicitly batches both changes and writes the latest one.

Flush waits for an earlier write to finish, then writes the captured pending batch. Concurrent submissions can remain for a later flush. Stop producers before a final boundary, or call Dispose, which stops accepting submissions before flushing accepted work. Later submissions are rejected with an ObjectDisposedException in their error output. Repeated disposal is safe.

Write failures invoke the callback outside the writer's locks, on the thread attempting the write. Failure and Flush(out error) also expose unresolved failures. A later successful write to the same path clears its failure; success on another path does not. A throwing failure callback retains both errors without stopping other paths. Failed writes are not automatically requeued. The underlying DurableFile guarantees and limits still apply; coalescing is per path within one writer, not a multi-file transaction.


Scene Helpers

Scene Queries

SceneHelper.IsSceneLoaded returns false for null, empty, or whitespace-only names and paths, including when an unsaved scene has an empty path. Valid names and paths are matched exactly.

Check if scene is loaded:

using WallstopStudios.UnityHelpers.Core.Helper;

bool loaded = SceneHelper.IsSceneLoaded("GameLevel");
// Checks by scene name or path

Get all scene paths (editor):

#if UNITY_EDITOR
string[] allScenes = SceneHelper.GetAllScenePaths();
// Returns all .unity files in project

string[] buildScenes = SceneHelper.GetScenesInBuild();
// Returns only scenes in Build Settings
#endif

Temporary Scene Loading

Constructing SceneHelper.SceneLoadScope with a null, empty, or whitespace-only path does nothing: it loads no scene, invokes no callback, and completes disposal immediately.

Call retrieval and SceneLoadScope construction on Unity's main thread. Retrieval accepts loaded scene names or paths, including nonactive scenes, and returns inactive objects too. Already loaded scenes are borrowed: disposing a result preserves their objects, active scene, and loaded scene count. Name matches are checked before resolving Build Settings aliases.

In players, new loads use scenes available to Unity, including packed Build Settings scenes; they do not require .unity source files on disk. Editor tools may also load scene assets outside Build Settings. Blank or unavailable inputs return empty/default results.

Load scene, extract data, unload owned scenes:

using WallstopStudios.UnityHelpers.Core.Helper;
using WallstopStudios.UnityHelpers.Utils;

DeferredDisposalResult<LevelConfig> result =
    await SceneHelper.GetObjectOfTypeInScene<LevelConfig>("Scenes/LevelData");
try
{
    LevelConfig config = result.result;
    if (config != null)
    {
        // Read configuration before disposing an owned scene.
    }
}
finally
{
    await result.DisposeAsync();
}

Retrieval disposal runs immediately on the calling main thread or posts to the Unity synchronization context captured during retrieval. It does not depend on dispatcher delivery. Await disposal before considering cleanup complete; a missing context or an unload failure faults the returned operation.

A direct SceneLoadScope exposes LoadTask for the loaded scene or load/callback failure. Its disposal must run on Unity's main thread. Disposal during loading suppresses the user callback, waits for loading, then unloads the exact scene owned by that scope. Multiple loads of the same path retain distinct scene handles. Repeated disposal awaits the same cleanup, and callback failures remain observable while cleanup still unloads the owned scene. Scene-loaded subscriptions and callback captures are released after completion or failure. These helpers retain Unity's synchronous scene-loading API, which can stall a frame; they do not provide a streaming-performance guarantee.

Use for:

  • Extracting data from data-only scenes
  • Editor tools reading scene contents
  • Validation scripts
  • Testing scene contents

Advanced Utilities

DisposableScope

Use DisposableScope.Create for a short cleanup that belongs to a using block:

using WallstopStudios.UnityHelpers.Utils;

using DisposableScope scope = DisposableScope.Create(RestoreSetting);

Add actions with WithCleanup and dispose the final returned scope. Added actions run in reverse order, including when one throws:

using var scope = DisposableScope.Create(RestoreSetting).WithCleanup(DeleteTempFolder);

Pass a reporter when cleanup failures must be visible:

using DisposableScope scope = DisposableScope.Create(RestoreSetting, UnityEngine.Debug.LogException);

The reporter receives the original exception on the disposing thread. Chained cleanups inherit it, and later cleanup failures do not prevent earlier actions. Reporter exceptions are ignored so they cannot replace an exception already in flight. The one-argument overload retains silent cleanup.

Each layer is a value type. Copies share a disposal lease, so each action runs at most once even if several copies are disposed. Disposing a default scope or passing a null action is harmless, and Dispose never throws. For reverse ordering, keep the final scope and let its using block dispose it; disposing an earlier copy before the final scope can run that earlier action sooner. Concurrent disposal of copies still runs each action once, but ordering across threads is undefined.

The scope itself does not allocate after its lease slots have warmed up. Reuse noncapturing delegates when an allocation-free call site matters; a capturing lambda can allocate when it creates its delegate.


RestorableGlobal<T>

The problem: the obvious way to borrow a global for the length of a block captures the previous value in the scope's own field and restores from that field. Making the scope readonly fixes the per-copy "have I been disposed?" flag and fixes nothing here: every copy agrees about what to put back and none of them about whether it already has, so a second Dispose re-imposes a value the world has moved past. WUH014 reports the shape; this type is the answer.

using WallstopStudios.UnityHelpers.Core.Helper;

private static readonly RestorableGlobal<RenderTexture> ActiveTexture =
    new RestorableGlobal<RenderTexture>(
        () => RenderTexture.active,
        value => RenderTexture.active = value
    );

public static void BlitInto(RenderTexture target)
{
    using (ActiveTexture.Borrow(target))
    {
        GL.Clear(true, true, Color.clear);
    }
}

The scope holds an identifier rather than a value, and gives it back with a call to the owner. Identifiers are never reused, so a stale copy's release is a no-op instead of a re-imposition.

Nesting and out-of-order disposal. Nesting one borrow inside another is the ordinary case, so the rule is stated for any depth and any order:

  • The global always holds the value the newest live borrow asked for. Releasing an older borrow writes nothing — the newer borrow is still running and is still entitled to what it asked for.
  • The released borrow's restore value is inherited by the borrow above it, so the last release returns the global to the value it held before the outermost borrow, whatever order the releases happened in.
  • That inheritance is conditional: the borrow above only takes it over when what it captured is still the value the released borrow applied. Where something else wrote to the global in between, that write is what comes back.

Unwinding every newer borrow along with an out-of-order older one was rejected: it takes a value away from a scope that is still running.

Nothing throws. Disposing a default scope, disposing twice, disposing after ReleaseAll(), and a getter or setter that throws are all handled — the failure is logged and the bookkeeping stays consistent. TryBorrow reports whether the value actually took; IsHeld answers for every copy at once; Depth is how many borrows are live.

Cost. A borrow allocates nothing once the slot table has grown to the deepest nesting reached: the scope is a readonly struct, so using calls Dispose directly rather than through a boxed interface. Construction allocates the owner, its table and the two delegates, once.

Threading. A per-instance monitor guards the table, so concurrent borrows cannot corrupt it — and the getter and setter run under that monitor, which makes a borrow atomic against another thread's. A process-wide cell still has one value, so two threads borrowing at once last-writer-wins on the thing itself, and most globals worth borrowing (Unity's among them) are main-thread only regardless. Under SINGLE_THREADED the monitor is compiled out.


Unity-Aware Null Checks

The problem: Unity's == operator overload can be slow, and destroyed UnityEngine.Objects return true for == null but false for is null.

using WallstopStudios.UnityHelpers.Core.Helper;

GameObject obj = GetMaybeDestroyedObject();

// Proper Unity null check
bool isNull = Objects.Null(obj);
bool notNull = Objects.NotNull(obj);

Handles:

  • Destroyed UnityEngine.Objects
  • Actual null references
  • Optimized checks for non-Unity types

Cached Generic Type Classification

ObjectsTypeTraits<T> in WallstopStudios.UnityHelpers.Core.Helper exposes three read-only classifications cached once for each closed generic type. They describe the declared T:

Field Meaning
IsValueType T is a value type, including enums and nullable value types.
IsObjectType T is exactly System.Object. Other reference types return false.
IsUnityObject T is UnityEngine.Object or derives from it. Arrays and collections of Unity objects return false.
using WallstopStudios.UnityHelpers.Core.Helper;

bool nullableIsValueType = ObjectsTypeTraits<int?>.IsValueType; // true
bool exactlyObject = ObjectsTypeTraits<object>.IsObjectType; // true
bool componentIsUnityObject = ObjectsTypeTraits<UnityEngine.Component>.IsUnityObject; // true
bool declaredObjectIsUnityObject = ObjectsTypeTraits<object>.IsUnityObject; // false

An object variable holding a boxed struct or a GameObject retains the object classifications. The flags do not inspect an instance or change when a Unity object is destroyed. Use Objects.Null(value) for Unity-aware instance null checks. A nullable value type still has IsValueType == true when its value is null, so this flag does not establish non-nullness.

Hash Code Composition

Combine hash codes correctly:

using WallstopStudios.UnityHelpers.Core.Helper;

public class CompositeKey
{
    public string Name;
    public int Level;
    public Vector2 Position;

    public override int GetHashCode()
    {
        // FNV-1a mixing over each member's own hash code
        return Objects.HashCode(Name, Level, Position);
    }
}

Supports up to 20 parameters. The mixing step is FNV-1a, for good distribution.

Hash entire collections:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
int hash = Objects.EnumerableHashCode(numbers);

Use for:

  • Custom GetHashCode implementations
  • Dictionary keys with multiple fields

Not for anything that outlives the process. The mixing is fixed, but each argument contributes its ordinary GetHashCode() value, and those are not portable: .NET randomizes string hash codes per process, a UnityEngine.Object hashes to a session-local instance id, and any other type answers with whatever its author wrote. Two runs of the same build on the same machine can disagree. Persisting one of these values, sending it over a network, or comparing it against a stored copy will appear to work and then fail.


Stable Hashing for Saves and Networking

Unity object hashes remain stable after Destroy or DestroyImmediate, including values passed as object, spans, and sequences. Only a managed null reference hashes as null. This keeps dictionary and set keys reachable after their Unity objects are destroyed. Objects.Null and Objects.NotNull still use Unity's destroyed-object checks.

Objects.StableHash32V1 hashes bytes and nothing else, so its answer depends only on its arguments: the same bytes and the same seed produce the same value in every process, on every platform, and in every later version of this package. The algorithm is frozen -- that is what the V1 names -- so a future change arrives under a different name rather than as a new answer here.

using WallstopStudios.UnityHelpers.Core.Extension;
using WallstopStudios.UnityHelpers.Core.Helper;

byte[] payload = saveSlotName.GetBytes();
uint digest = Objects.StableHash32V1(payload, Objects.Fnv32OffsetBasis);

An empty span returns the seed unchanged, so chunks can be folded together by passing the previous result as the next seed. Encode text yourself, so the encoding is part of your format rather than an assumption of this one. Being a 32-bit non-cryptographic hash, it is for identity and change detection, never for security.

Objects.StableHash64V1(bytes, seed) provides the standard 64-bit FNV-1a variant. Its optional seed defaults to Objects.Fnv64OffsetBasis (14695981039346656037). It has the same frozen algorithm and chunk-folding contract as the 32-bit method. Encode text as UTF-8 when matching existing UTF-8 hashes or persisted scene identifiers. No byte-order conversion or terminating null byte is added.

using System.Text;
using WallstopStudios.UnityHelpers.Core.Helper;

ulong signature = Objects.StableHash64V1(Encoding.UTF8.GetBytes("foobar"));
// signature is 0x85944171f73967e8.

Objects.AppendStableHash64V1(hash, intValue) and (hash, longValue) append exactly four or eight little-endian two's-complement bytes without creating a byte array. An int and the same numeric value as a long therefore append different byte sequences. The byte order and signed representation are frozen across platforms.

Objects.StableHashUtf16Le64V1(text.AsSpan(), seed) hashes each raw UTF-16 code unit low byte first, then high byte. It does not normalize text, replace unpaired surrogates, or append a terminator. The optional seed defaults to Objects.Fnv64OffsetBasis. The explicit name preserves existing StableHash64V1(default) and StableHash64V1(default, seed) byte-span calls, including literal seeds. The scalar append forms also use a distinct name for this source compatibility. UTF-16 and UTF-8 hashes differ: use the format your persisted data already uses.

Objects.Fnv1aWordFold64(words, seed) accepts signed or unsigned 64-bit word spans. Each whole word contributes one XOR and multiply; signed words contribute their two's-complement bits. It returns the seed for empty input and supports chunk folding. This first word-fold algorithm is permanently frozen; later algorithms will use different names.

Whole-word folding is deliberately weak. A difference confined to high bits never reaches the lower bits, even after more words are folded. It is useful when reproducing an existing word signature, and gives different results from hashing those words' bytes. Keep exact state equality when resolving collisions; use a stronger digest for content identity or security.

using System;
using WallstopStudios.UnityHelpers.Core.Helper;

ulong hash = Objects.AppendStableHash64V1(Objects.Fnv64OffsetBasis, -42);
hash = Objects.AppendStableHash64V1(hash, long.MinValue);
ulong textHash = Objects.StableHashUtf16Le64V1("example".AsSpan());
long[] words = { 0, 1, -1, long.MinValue };
ulong wordSignature = Objects.Fnv1aWordFold64(words);

The constants and test vectors follow the FNV specification. Both FNV variants allow collisions and are non-cryptographic.


SHA-256 Digests (Objects)

When identity needs to survive a hostile reader: Objects.Sha256Hex hashes text (as UTF-8) or bytes into the standard 64-character lowercase hex digest, and Objects.TrySha256HexOfFile hashes a file, reporting a missing or unreadable file with false instead of throwing.

using WallstopStudios.UnityHelpers.Core.Helper;

string digest = Objects.Sha256Hex("save-slot-3");
// "af3a7b3f7a85f558898483659933264fe4180ccf7eef520d37df1ad063e9128d"

Use it where a 32-bit stable hash is not enough: content-addressed cache keys, detecting whether a download or import actually changed, and tamper checks on player-supplied data. Unlike StableHash32V1, no adversary can craft a second input with the same digest, and unlike the HashCode family, the value is stable across processes and platforms.

using WallstopStudios.UnityHelpers.Core.Helper;
using UnityEngine;

string texturePath = "Assets/Sprites/hero.png";
string previousDigest = "af3a7b3f7a85f558898483659933264fe4180ccf7eef520d37df1ad063e9128d";

bool changed =
    !Objects.TrySha256HexOfFile(texturePath, out string fileDigest)
    || fileDigest != previousDigest;

Debug.Log($"Texture changed: {changed}");

Texture and Sprite Pixel Helpers

SpriteArtBounds.TryGetLocalArtBounds measures drawn pixel cells instead of the full sprite rectangle or its extruded mesh. It excludes transparent borders and uses the sprite pivot and pixels per unit. The Editor reads source PNG pixels and honors the importer's alpha source without changing import settings. Grayscale alpha uses the mean RGB value; disabling alpha treats every source pixel as opaque. Players require readable texture pixels. Readable rectangular, unrotated atlas sprites are supported, including trimmed rectangles and off-center pivots. Tight or rotated atlas fallbacks are refused; measure their original PNG sprites in the Editor instead. Fully transparent sprites and unavailable pixels return false, empty bounds, and a reason.

The sprite overload and SpriteMaskReader refuse separate alpha textures when original source pixels are unavailable, so an opaque color texture cannot hide transparency stored elsewhere. Read an exact SpriteAlphaMask, for example from the original PNG in the Editor, and use the mask overload for those sprites.

The sprite overload scans effective alpha directly without creating a mask array. Both overloads stop scanning a row after finding its two visible edges. Dense masks benefit most; transparent cached masks measured 6–9% slower. See the row-scan measurements and replay. Read bounds when the sprite or its source changes. If you already hold a SpriteAlphaMask, use the mask overload to avoid reading the texture again. The mask overload checks dimensions and coordinates, borrows the pixel array, and allocates no result storage.

Mask bounds subtract the stored float pivot from pixel corners in double precision, then multiply by the stored float UnitsPerPixel. Bounds centres and sizes round to float at the end. This can differ by a bit from float subtraction followed by division by pixels per unit. Plan one deliberate re-bake when migrating a byte-compared scene bake. AsDrawn preserves center.z; LowestCornerY transforms corners in that same local Z plane.

SpriteArtBounds.TryGetCentreOfLargestDarkestInkRegion(sprite, minimumShare, out Vector2 centre, out string error) finds a colour region's centroid for sprite analysis. It reads source PNG pixels in the Editor, including unreadable imports, or readable unpacked textures at runtime. Atlas-only pixels and separate alpha textures without a source PNG are refused. It does not change import settings.

  • Only fully opaque pixels count, using the importer's effective alpha policy in the Editor.
  • A colour must cover at least minimumShare of those pixels. The share must be finite and between zero and one; zero permits any present colour.
  • Darkness uses Rec. 601 weights 299 * R + 587 * G + 114 * B. Equal luma chooses the lower packed RGB value, so dictionary order cannot change the result.
  • Regions join only exact RGB matches across horizontal or vertical neighbors. Diagonal contact stays separate. The largest region wins; equal sizes choose the first bottom-left row-major seed.
  • The result averages pixel centres in double precision, then applies the same pivot and pixel size mapping as the alpha reader. It is a centroid, which can differ from a bounding-box centre.
  • Missing pixels, no fully opaque colour, no qualifying colour, and unrepresentable local coordinates return false, a zero centre, and a reason. Scratch arrays and colour counts are pooled; the texture pixel read still allocates its colour array.

The ink traversal measurements describe a measured checkerboard improvement and the limits of that comparison.

Apply AsDrawn for renderer flips, then LowestCornerY for world position, rotation and scale. Flips mirror around the renderer origin. The lowest corner can differ from the transformed local bottom edge when the renderer is rotated.

using UnityEngine;
using WallstopStudios.UnityHelpers.Utils;

public static class SpriteFrontEdge
{
    public static bool TryMeasure(SpriteRenderer renderer, out float worldY, out string error)
    {
        if (renderer == null)
        {
            error = "A renderer is required.";
            worldY = 0f;
            return false;
        }
        if (!SpriteArtBounds.TryGetLocalArtBounds(renderer.sprite, out Bounds local, out error))
        {
            worldY = 0f;
            return false;
        }
        Bounds drawn = SpriteArtBounds.AsDrawn(local, renderer.flipX, renderer.flipY);
        error = null;
        worldY = SpriteArtBounds.LowestCornerY(renderer.localToWorldMatrix, drawn);
        return true;
    }
}

SpriteHelpers.RotateTexture90, RotateTexture180 and ExtractSpriteRect produce a new texture and leave the source untouched. They preserve writable source formats and use RGBA32 for readable compressed sources. A quarter turn swaps dimensions. Sprite extraction reads a small sprite's rectangle directly when supported, and uses the lower-memory full-texture path for large regions or formats such as Crunch that reject region reads.

using WallstopStudios.UnityHelpers.Core.Helper;
using UnityEngine;

Texture2D source = new Texture2D(64, 128, TextureFormat.RGBA32, false);
source.SetPixels32(new Color32[64 * 128]);
source.Apply();

Texture2D clockwise = source.RotateTexture90(clockwise: true);
Texture2D upsideDown = source.RotateTexture180();

Both return null, with a logged reason, when the texture is not readable or its format refuses pixel writes, so a compressed atlas never throws mid-load. Each returned texture is a new allocation: destroy it when finished with it.

using WallstopStudios.UnityHelpers.Core.Helper;
using UnityEngine;

Texture2D sheet = new Texture2D(256, 256, TextureFormat.RGBA32, false);
sheet.Apply();
Sprite sprite = Sprite.Create(sheet, new Rect(0, 0, 32, 32), new Vector2(0.5f, 0.5f));

Texture2D extracted = sprite.ExtractSpriteRect();

Packed sprites must use rectangular packing with packingRotation == None. Tight packing, horizontal or vertical flips, half turns, and other rotation metadata return null with an error before the helper reads textureRect or copies pixels. Disable rotation and tight packing on an atlas used for extraction. Unrotated rectangular atlas regions keep their existing pixel behavior.

Native atlas probes on 2026-11-09 verified 30 packed, unrotated sprites against independent source-pixel gradients on Unity 6000.6.7f1. Rotation was enabled, but the packer used separate pages and produced no rotated sprites. This does not qualify the rotated-sprite acceptance case in #1135, which remains open. The probe sources, results and process logs remain in ignored local storage.

ExtractSpriteRect copies the sprite's textureRect region from its source sheet, so it reads a sprite out of a larger sheet without touching the sheet itself. The sheet must be readable, and a rect that leaves the sheet is reported as a logged null rather than an out-of-range read.


Formatting

Human-readable byte counts:

using WallstopStudios.UnityHelpers.Core.Helper;

long bytes = 1536000;
string formatted = FormattingHelpers.FormatBytes(bytes);
// Result: "1.46 MB"

Auto-scales to B, KB, MB, GB, TB.

Use for:

  • File size displays
  • Memory usage UI
  • Profiling output
  • Download progress

Multi-Dimensional Array Iteration

Enumerate 2D/3D array indices:

using WallstopStudios.UnityHelpers.Core.Helper;

int[,] grid = new int[10, 10];

// Get all indices as tuples
foreach (var (x, y) in IterationHelpers.IndexOver(grid))
{
    grid[x, y] = x + y;
}

// Buffered (reduces allocations)
using (var buffer = Buffers<(int, int)>.List.Get())
{
    IterationHelpers.IndexOver(grid, buffer.Value);
    foreach (var (x, y) in buffer.Value)
    {
        // Process
    }
}

Also supports 3D arrays with (int, int, int) tuples.


Binary Array Conversion

Marshalling between int[] and byte[]:

using WallstopStudios.UnityHelpers.Core.Helper;

int[] ints = { 1, 2, 3, 4, 5 };

// Convert to bytes (uses Buffer.BlockCopy)
byte[] bytes = ArrayConverter.IntArrayToByteArrayBlockCopy(ints);

// Convert back
int[] restored = ArrayConverter.ByteArrayToIntArrayBlockCopy(bytes);

Use for:

  • Network serialization
  • Binary file formats
  • Save game data
  • High-performance data conversion

Performance: Uses native memory copy (Buffer.BlockCopy) which is faster than element-by-element loops due to optimized native implementation, though both are O(n).


Bit Manipulation (BitOps)

One home for the bit math every system re-derives: BitOps centralizes the SWAR popcount, trailing zero count, floor log2, highest-bit isolation, power-of-two detection and power-of-two ceiling that data structures, sorters and capacity sizing keep re-implementing. Every method is a pure, allocation-free function of its inputs; signed overloads interpret their argument as the two's-complement bit pattern.

The unsigned Log2 forms use bit smearing and portable de Bruijn indexing instead of a chain of input comparisons. Log2(0) and Log2(1) return zero. Logarithm and trailing-zero lookup data use constant read-only spans. Mono uses fixed array caches initialized once because its span construction is slower on this path; warm calls create no lookup arrays. See the native measurements and replay.

using WallstopStudios.UnityHelpers.Core.Helper;

int liveEnemies = BitOps.PopCount(0b1011UL); // 3
int bucket = BitOps.Log2(77) + 1; // floor log2 + 1
int lowestFlag = BitOps.TrailingZeroCount(0b1010_0000); // lowest set bit, 32 when none
uint poolSize = BitOps.NextPowerOfTwo(37U); // smallest power of two >= 37
bool isFlag = BitOps.IsPowerOfTwo(1UL << 7); // exactly one bit set

NextPowerOfTwo throws ArgumentOutOfRangeException when no exact power of two is representable (negative values, or values beyond 2^30 / 2^31 / 2^62 / 2^63 for int / uint / long / ulong) instead of overflowing silently.


Set-Bit Traversal and Graph Reachability

BitOps.SetBits(ulong) returns a struct traversal of the mask's set-bit indices in ascending order. foreach does not box it or allocate an iterator. BitOps.SelectBit(mask, rank) returns the zero-based ranked set-bit index, or -1 for a negative or exhausted rank. Trailing-zero counts use a portable de Bruijn lookup; zero still returns 64 for ulong and 32 for uint. BitSet.GetSetBits and EnumerateSetIndices skip unset words and visit set bits in order; the latter keeps its existing IEnumerable<int> API and iterator allocation. Between iterator moves it observes changes ahead of its cursor, including growth, clearing and shrinking.

using WallstopStudios.UnityHelpers.Core.Helper;

foreach (int index in BitOps.SetBits(0b1010UL))
{
    UnityEngine.Debug.Log(index); // 1, then 3
}
int second = BitOps.SelectBit(0b1010UL, 1); // 3

GraphReach.Reachable(nodeCount, edges, root, BitSet reached) replaces a reusable result with all nodes reachable along directed edges, including the root itself. It runs in O(V + E) time using pooled adjacency and queue arrays. Size the result once and warm the scratch pools for calls without garbage allocation. Duplicate edges, self-links, cycles and disconnected nodes are supported. A null result, nonpositive node count, invalid root, or invalid edge returns false; a supplied result is cleared on failure. Every edge is validated, including edges in unreachable components. Neither input order nor the input span is changed.

For up to 64 nodes, GraphReach.Reachable(nodeCount, edges, root) returns a ulong mask using stack storage. Invalid input, including more than 64 nodes, returns zero. The input graph and result must not be changed concurrently with either call.

using WallstopStudios.UnityHelpers.Core.DataStructure;
using WallstopStudios.UnityHelpers.Core.Helper;

(int from, int to)[] edges = { (0, 1), (1, 2), (2, 0) };
BitSet reached = new(4);
bool valid = GraphReach.Reachable(4, edges, 0, reached);
ulong mask = GraphReach.Reachable(4, edges, 0); // bits 0, 1 and 2

Descriptive Statistics (WallMath)

One home for the numbers gameplay code keeps re-deriving: WallMath.Median, Percentile, Mean and StandardDeviation read an IReadOnlyList directly, so a List<T>, a T[] or a pooled buffer all work with no intermediate copy on your side. TryClopperPearsonInterval computes an exact confidence interval for a measured binomial success rate. TryExactSignTest compares paired measurements without a large-sample approximation. TryFisherExactTest compares two binary groups with fixed margins. Sorting for median and percentile happens on a pooled internal copy, so your list is never reordered.

Mean and StandardDeviation snapshot numeric List<T> inputs into privately owned pooled arrays and return them before the call exits. No disposable handle escapes. Array inputs retain their direct path, and other IReadOnlyList<T> implementations retain their indexed reads. Population/sample behavior, accumulation order and caller contents remain unchanged.

using System.Collections.Generic;
using WallstopStudios.UnityHelpers.Core.Helper;

List<float> runTimes = new List<float> { 2.1f, 0.9f, 1.7f, 3.3f, 1.2f };

float median = runTimes.Median(); // 1.7
float p95 = runTimes.Percentile(0.95f); // near the slowest run
float mean = runTimes.Mean(); // 1.84
float spread = runTimes.StandardDeviation(); // population spread around the mean

Conventions, chosen once so callers do not have to guess:

  • Median of an even count averages the two middle elements; the halving is done in double, so extreme magnitudes cannot overflow.
  • Percentile interpolates linearly between closest ranks (0 is the minimum, 1 the maximum). Finite opposite extremes stay finite, and primitive conversions do not box the elements. Exact ranks retain their stored value. Interior interpolation preserves equal infinities, returns the infinite endpoint when only one endpoint is infinite, and returns NaN between opposite infinities. Results are undefined for data containing NaN; a NaN or out-of-range percentile throws.
  • Mean accumulates in double, so a float sum cannot lose magnitude and an int sum cannot overflow. Integral data returns double, matching Enumerable.Average.
  • StandardDeviation is the population standard deviation by default; pass sample: true for Bessel's correction when the data is a sample of a larger population.

For unsorted byte channels, WallMath.TryMedian accepts arrays, read-only spans, and IReadOnlyList<byte>. Arrays and exact List<byte> instances use concrete loops even through the read-only interface. Derived lists and other implementations retain interface indexing. It counts values in a fixed 256-bin stack histogram, taking O(n + 256) time without copying, sorting, or mutating the input. Even counts return the average of both middle values as a double. Null or empty byte input returns false and NaN. The existing double-span overload still requires ascending sorted input.

A three-process .NET 9 Linux helper comparison at 8, 256 and 4,096 elements supports this dispatch: paired median candidate/baseline ratios for interface arrays were 0.886, 0.403 and 0.262; list ratios were 0.937, 0.496 and 0.356. The smallest unchanged-array and wrapped-list controls regressed about 3%. These observations do not qualify Unity or player throughput. All timed calls allocated zero bytes under a working 4,120-byte positive control. See the raw samples and method, sources and process records.

For a binary outcome, use an exact Clopper-Pearson interval when the sample is small or the observed rate is close to zero or one:

using WallstopStudios.UnityHelpers.Core.Helper;

bool measured = WallMath.TryClopperPearsonInterval(
    successes: 17,
    trials: 20,
    confidenceLevel: 0.95,
    out double lowerRate,
    out double upperRate
);

The interval is equal-tailed and includes both endpoints. Zero successes produces a lower bound of zero; success on every trial produces an upper bound of one. Invalid counts, a non-positive trial count, or a non-finite/confidence level outside the open interval (0, 1) return false and set both outputs to zero.

For paired measurements, count how many non-tied pairs improved and regressed. The exact sign test returns the probability of an outcome at least as imbalanced under an equal-chance null hypothesis:

using WallstopStudios.UnityHelpers.Core.Helper;

bool compared = WallMath.TryExactSignTest(
    positiveDifferences: 8,
    negativeDifferences: 2,
    out double twoSidedPValue
); // p = 0.109375

Exclude tied pairs before calling the method. Negative counts, no non-tied pairs, or a combined count beyond int.MaxValue return false and clear the output. The calculation uses the exact binomial tail and remains bounded for large counts; extremely small probabilities can round to zero in double.

For two independent binary groups, Fisher's exact test sums every fixed-margin table no more likely than the observed table:

using WallstopStudios.UnityHelpers.Core.Helper;

bool compared = WallMath.TryFisherExactTest(
    upperLeft: 1,
    upperRight: 9,
    lowerLeft: 11,
    lowerRight: 3,
    out double twoSidedPValue
); // p is about 0.00276

Negative counts, an empty table, totals beyond int.MaxValue, or more than one million possible fixed-margin tables return false and clear the output. The table-count limit bounds work for data that needs a large-sample method instead.

For stratified binary outcomes, estimate the common odds ratio with Mantel-Haenszel pooling:

using WallstopStudios.UnityHelpers.Core.Helper;

(int upperLeft, int upperRight, int lowerLeft, int lowerRight)[] strata =
{
    (1, 9, 11, 3),
    (8, 2, 4, 6)
};
bool estimated = WallMath.TryMantelHaenszelOddsRatio(strata, out double oddsRatio);
// oddsRatio = 101 / 181, about 0.558

Rows and columns must have consistent meanings across strata. With cells (a, b, c, d) and total n, pooling computes sum(a*d/n) / sum(b*c/n), as in statsmodels' pooled odds ratio. Empty strata contribute nothing. Null or empty input, any negative cell, and an undefined zero-over-zero ratio return false and clear the output. A zero numerator produces zero; a positive numerator with a zero denominator produces positive infinity. All non-negative int cell counts are supported, including tables whose total exceeds int.MaxValue. The method reads the existing buffer without allocating or changing it. No continuity correction is added. This is a common-effect estimate, with independent observations within and between strata; it does not supply a confidence interval, an exact significance test, or a test of homogeneity.

For an already computed chi-square statistic, get its upper-tail probability directly:

using WallstopStudios.UnityHelpers.Core.Helper;

bool evaluated = WallMath.TryChiSquareSurvival(
    statistic: 3.841458820694124,
    degreesOfFreedom: 1,
    out double upperTailProbability
); // about 0.05

The probability is Q(degreesOfFreedom / 2, statistic / 2), the regularized upper incomplete gamma function. Its evaluation uses the gamma series and continued fraction, with a stable logarithmic prefactor for large degrees of freedom. This evaluates the chi-square distribution; whether that distribution is appropriate for a particular test remains the caller's statistical assumption. It does not turn a small-sample chi-square test into an exact test.

Degrees of freedom must be a positive int. A zero statistic returns one, positive infinity returns zero, and negative or NaN statistics return false. Both numerical paths have a one-million-iteration convergence limit and fail with false and zero output if convergence cannot be established. Extremely small probabilities can underflow to zero; ordinary small tails are evaluated directly rather than by subtracting a cumulative probability from one. The method allocates no scratch buffer. Reference tests cover finite exponential sums for even degrees, independently evaluated small tails, and high-precision density quadrature at int.MaxValue degrees of freedom.

using WallstopStudios.UnityHelpers.Core.Helper;

int[] waveSizes = { 8, 12, 10, 15, 9, 11, 14, 10 };

double averageWave = waveSizes.Mean(); // 11.125
double medianWave = waveSizes.Median(); // 10.5
double p90Wave = waveSizes.Percentile(0.9); // 14.3

The descriptive list methods throw on an empty list and a null receiver: a statistic of nothing is undefined, and the package fails closed rather than inventing a zero.


Custom Comparers

Create IComparer from lambda:

using WallstopStudios.UnityHelpers.Core.Helper;

public sealed class Enemy : MonoBehaviour { public int health; }

var enemies = new List<Enemy>();

// Sort by health descending
enemies.Sort(new FuncBasedComparer<Enemy>((a, b) =>
    b.health.CompareTo(a.health) // Descending
));

Reverse any comparer:

var comparer = Comparer<int>.Default;
var reversed = new ReverseComparer<int>(comparer);

// Now sorts descending
list.Sort(reversed);

Browser String Storage

BrowserStorage provides scoped string storage. WebGL players use the browser's localStorage. Editor and other players use PlayerPrefs. Backend selection happens at compile time. A blocked or full browser store returns failure rather than switching to another store and hiding existing data.

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");

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.

Use BrowserStorage.Unscoped to read saves already stored under raw keys by another browser bridge or by PlayerPrefs. Its keys pass through unchanged. The ordinary scoped constructor still isolates its keys; passing a blank scope does not enable raw mode. Raw mode shares the backend's key namespace with other callers. It does not copy, migrate, or delete existing saves when created.

TryHasKey(key, out bool exists) distinguishes absence from backend failure. It returns true with exists == true for a present key, including an empty value, and true with exists == false for an absent key. Invalid keys, invalid scoped stores, and blocked storage return false with exists == false. Existence does not validate the stored value's text or type.

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. Scoped operations construct a prefixed key; raw operations reuse the supplied key. Reads allocate their returned string.

See Unity's browser scripting guide and PlayerPrefs documentation for native string marshalling and platform storage limits.

WebGL startup class 115 diagnostics

If a Unity 6000.5.2f1 WebGL build logs Could not produce class with ID 115, preserve its output and use Clean Build in Build Profiles. A build script can pass BuildOptions.CleanBuildCache to BuildPipeline.BuildPlayer, as described in Unity's clean-build guide. Keep the browser console visible when checking the rebuilt player.

If a clean build does not help, close Unity and move Library aside before rebuilding imported state. Keep a copy of the failing output and compare the same source and build settings after recovery. This rebuild leaves browser storage data intact and does not require weaker stripping settings. A successful storage read does not by itself show that the startup registration error is resolved; check the browser console as well.

Environment Detection

CI/CD Detection

Detect if running in a CI environment:

using WallstopStudios.UnityHelpers.Core.Helper;

if (Helpers.IsRunningInContinuousIntegration)
{
    // Skip interactive dialogs, use defaults
}

if (Helpers.IsRunningInBatchMode)
{
    // Running headless (no graphics device)
}

Read a named value from the current process, or use the deterministic overload when parsing a stored command line. Names are matched exactly and a trailing flag has no value:

string scene = Helpers.GetCommandLineArgument("-scene");
List<string> scenes = Helpers.GetCommandLineArguments(
    new[] { "game", "-scene", "Town", "-scene", "Dungeon" },
    "-scene"
);

GetCommandLineArguments preserves repeated values in order. Both helpers fail soft for null input or a blank name, and the current-process overload returns null instead of throwing when process arguments are unavailable. Blank names are rejected before reading process arguments. Names with surrounding spaces match exactly, and values retain literal whitespace.

Supported CI systems (checked via environment variables):

CI System Environment Variable
Generic CI CI
GitHub Actions GITHUB_ACTIONS
GitLab CI GITLAB_CI
Jenkins JENKINS_URL
Travis CI TRAVIS
CircleCI CIRCLECI
Azure Pipelines TF_BUILD
TeamCity TEAMCITY_VERSION
Buildkite BUILDKITE
AWS CodeBuild CODEBUILD_BUILD_ID
Bitbucket Pipelines BITBUCKET_BUILD_NUMBER
AppVeyor APPVEYOR
Drone CI DRONE
Unity CI UNITY_CI
Unity Tests UNITY_TESTS

Check specific environment variables:

using WallstopStudios.UnityHelpers.Core.Helper;

// Check if a specific environment variable is set (non-empty, non-whitespace)
bool onGitHub = Helpers.IsEnvironmentVariableSet(
    Helpers.CiEnvironmentVariables.GitHubActions
);

bool onJenkins = Helpers.IsEnvironmentVariableSet(
    Helpers.CiEnvironmentVariables.JenkinsUrl
);

// Access all known CI variable names
foreach (string varName in Helpers.CiEnvironmentVariables.All)
{
    if (Helpers.IsEnvironmentVariableSet(varName))
    {
        Debug.Log($"CI detected via: {varName}");
    }
}

Use for:

  • Skipping interactive dialogs in CI
  • Disabling expensive editor visualizations
  • Conditional test behavior
  • Build automation scripts
  • Asset processors that shouldn't run headless

Best Practices

Performance

  • Cache lookups: Helpers.Find<T>() caches, but don't call every frame anyway
  • Use buffered variants: IterateOverAllChildrenRecursively with buffers for hot paths
  • Main thread dispatch: Don't send hundreds of tiny tasks, batch work
  • Hierarchy traversal: Use breadth-first with depth limits for large hierarchies

Threading

  • Main thread rule: Only Unity APIs need main thread, pure C# can stay on background threads
  • Avoid blocking: Don't wait for main thread results in tight loops
  • CancellationToken: Support cancellation for long operations

Architecture

  • Component vs Helper: Components (MonoBehaviours) for per-object state, Helpers for stateless operations
  • Static method smell: If you need instance state, use a component instead
  • Editor/Runtime split: Use #if UNITY_EDITOR guards for editor-only helpers

Code Organization

  • Namespace imports: Use using WallstopStudios.UnityHelpers.Core.Helper; at top of file
  • Don't extend helpers: These are sealed utility classes, not inheritance hierarchies
  • Prefer composition: Use helpers from components, don't try to combine them

Related Documentation

Stopwatch Timestamps

Added in the next release. Use StopwatchTimestamp from WallstopStudios.UnityHelpers.Core.Helper when you need elapsed time without creating a Stopwatch object. Since accepts a timestamp from Stopwatch.GetTimestamp() and returns a signed TimeSpan. Use SecondsSince(start) to get signed elapsed seconds directly; it shares the allocation-free counter conversion used by both shared pools. ToSeconds, ToMilliseconds and ToNanoseconds accept counter ticks, not TimeSpan ticks.

using System;
using System.Diagnostics;
using WallstopStudios.UnityHelpers.Core.Helper;

public static class LoadTimer
{
    public static TimeSpan Measure(Action load)
    {
        long start = Stopwatch.GetTimestamp();
        load?.Invoke();
        return StopwatchTimestamp.Since(start);
    }

    public static long CounterTicksForFrameBudget()
    {
        return StopwatchTimestamp.TicksFrom(TimeSpan.FromMilliseconds(16));
    }
}

TicksFrom truncates fractional counter ticks toward zero and saturates at long.MinValue or long.MaxValue when a duration exceeds the counter's range. It keeps integer precision for large durations. Since uses wrapping counter subtraction, truncates to TimeSpan ticks and saturates at TimeSpan limits. A future start can produce a negative duration. Floating-point conversions return approximate values in the requested units; timestamps are meaningful only for the same counter and runtime.

📚 Documentation

Getting Started

Inspector Features

Effects System

Relational Components

Serialization

Spatial Trees

Logging

Utilities

Editor Tools

Guides

Performance

Project

Clone this wiki locally