Skip to content

Helper Utilities

LoL Engine ships a small set of runtime helpers alongside the core services. This page documents the helpers that currently exist in the package. It intentionally does not list older math, geometry, string, vector, quaternion, or circular-list helpers because those files are not part of the current Assets/LoLEngine/Runtime/Scripts/Helpers surface.

Locations

Area Namespace Files
Audio helper components LoLEngine.Helpers.Audio Runtime/Scripts/Helpers/Audio/
Shuffle bag LoLEngine.Helpers.Extensions Runtime/Scripts/Helpers/Extensions/ShuffleBag.cs
General runtime helpers LoLEngine.Runtime Runtime/Scripts/Runtime/
Runtime utility types LoLEngine.Runtime.Utility Runtime/Scripts/Runtime/Utility/
Model registry LoLEngine.Runtime.Models Runtime/Scripts/Runtime/Models/
Misc utility types LoLEngine.Utility Runtime/Scripts/Utility/
Odds helpers LoLEngine.Utility.Odds Runtime/Scripts/Utility/Odds/

Audio Helper Components

These are optional MonoBehaviours that wrap IAudioService for common Inspector-driven workflows. They require the Audio Service to be enabled in ServiceConfiguration.

SimpleAudioPlayer

Add from Add Component > LoLEngine > Helpers > Simple Audio Player.

Use it for a single configured audio ID, such as scene ambience, a looping music bed, or a UI sound.

using LoLEngine.Helpers.Audio;
using UnityEngine;

public class Doorbell : MonoBehaviour
{
    [SerializeField] private SimpleAudioPlayer player;

    public void Ring()
    {
        player.SetAudioId("Audio/UI/Doorbell", playImmediately: true);
    }
}

Important public members:

  • Play() / PlayAsync() starts the configured audio ID.
  • Stop() fades out the current handle using the configured fade-out duration.
  • SetAudioId(string newAudioId, bool playImmediately = false) updates the configured ID.
  • SetAudioIdAsync(string newAudioId) updates and immediately plays with async loading.
  • IsPlaying reports whether the current handle is still playing.
  • CurrentAudioId returns the configured audio ID.

AdvancedAudioPlayer

Add from Add Component > LoLEngine > Helpers > Advanced Audio Player.

Use it when you need Inspector-configured playback options such as volume, pitch, looping, spatial settings, fade settings, and track assignment.

using LoLEngine.Helpers.Audio;
using UnityEngine;

public class MusicZone : MonoBehaviour
{
    [SerializeField] private AdvancedAudioPlayer musicPlayer;

    private async void OnTriggerEnter(Collider other)
    {
        musicPlayer.SetAudioId("Audio/Music/Forest", playImmediately: false);
        await musicPlayer.PreloadAudio();
        await musicPlayer.PlayAsync();
    }

    private void OnTriggerExit(Collider other)
    {
        musicPlayer.Stop();
    }
}

Important public members:

  • Play() / PlayAsync() starts the configured clip.
  • PlaySync() uses the synchronous audio path for already-loaded clips.
  • Stop() and Stop(float customFadeOut) stop the current handle.
  • PreloadAudio() preloads the configured audio ID through the audio service.
  • SetAudioId(...) / SetAudioIdAsync(...) update the configured ID.
  • GetPerformanceInfo() returns last load time, preload state, and last play time.

AudioPreloadManager

Use this component to preload groups of audio IDs before a scene, encounter, or UI flow needs them.

using LoLEngine.Helpers.Audio;
using UnityEngine;

public class EncounterAudioLoader : MonoBehaviour
{
    [SerializeField] private AudioPreloadManager preloadManager;

    private async void Start()
    {
        await preloadManager.PreloadAudioBatchAsync(
            new[] { "Audio/SFX/Hit", "Audio/SFX/Crit", "Audio/Music/Battle" },
            AudioPriority.Important,
            progress => Debug.Log($"Audio preload: {progress:P0}")
        );
    }
}

Useful methods:

  • PreloadAudioAsync(string audioId, AudioPriority priority = AudioPriority.Normal)
  • PreloadAudioBatchAsync(IEnumerable<string> audioIds, AudioPriority priority = AudioPriority.Normal, Action<float> progressCallback = null)
  • IsPreloaded(string audioId)
  • MarkAsUsed(string audioId)
  • UnloadAudio(string audioId)
  • GetStats()

Related enums in LoLEngine.Helpers.Audio:

  • AudioPriority
  • AudioLoadingStrategy
  • AudioCategory

For direct service usage, see Audio.md and AudioHelpers.md.

ShuffleBag

ShuffleBag<T> provides weighted draws without simply calling Random.Range every time. Add items with quantities, then call Pick().

using LoLEngine.Helpers.Extensions;
using UnityEngine;

var bag = new ShuffleBag<string>();
bag.Add("Common", 6);
bag.Add("Rare", 2);
bag.Add("Legendary", 1);

Debug.Log(bag.Pick());

Useful members:

  • Capacity
  • Size
  • Add(T item, int quantity)
  • Pick()
  • Reset()
  • Clear()
  • Shuffle()

Pick() throws InvalidOperationException if the bag is empty.

TypedPoolBag

TypedPoolBag<TKey, TItem> is a bucketed no-replacement draw helper. It is useful for rewards or content pools where you prefer one bucket, then cascade to lower-priority buckets when the preferred bucket is empty.

using LoLEngine.Core.Rng;
using LoLEngine.Utility;

var rng = new Rng(12345);

var rewards = new TypedPoolBag<string, string>()
    .AddBucket("Rare", new[] { "Relic_A", "Relic_B" })
    .AddBucket("Common", new[] { "Potion", "Gold" })
    .WithFilter(item => item != "Relic_A")
    .Shuffle(ref rng);

string reward = rewards.Draw("Rare");

Useful members:

  • AddBucket(TKey key, IEnumerable<TItem> items)
  • WithFilter(Func<TItem, bool> isAllowed)
  • Shuffle(ref Rng rng)
  • Draw(TKey preferredKey)
  • TotalCount
  • CountInBucket(TKey key)
  • IsEmpty(TKey key)
  • IsExhausted
  • GetRemainingItems(TKey key)
  • BucketKeys

Draw throws PoolExhaustedException when no allowed items remain.

Odds Helpers

LoLEngine.Utility.Odds contains base types for odds-based systems.

  • AbstractOdds<TOutcome> is the base class for stateful odds rollers.
  • AntiPityOdds<T> adjusts effective weights after each roll to reduce streaks.
  • PoolExhaustedException is shared with pool-style draw helpers.

These helpers use LoLEngine.Core.Rng.Rng, so their output can be deterministic and saveable.

Runtime Wait Helpers

LoLEngine.Runtime.WaitFor caches common Unity yield instructions.

using System.Collections;
using LoLEngine.Runtime;
using UnityEngine;

public class Flash : MonoBehaviour
{
    private IEnumerator Start()
    {
        yield return WaitFor.Seconds(0.25f);
        yield return WaitFor.EndOfFrame;
        yield return WaitFor.FixedUpdate;
    }
}

Use WaitFor.Seconds(float seconds) when the same wait durations occur repeatedly and you want to avoid repeated WaitForSeconds allocations.

ServiceAwaiter

ServiceAwaiter is in LoLEngine.Runtime. Use it before resolving services from ServiceLocator.

using LoLEngine.Core.Audio.Interfaces;
using LoLEngine.Core.ServiceManagement.Service;
using LoLEngine.Runtime;
using UnityEngine;

public class UsesAudio : MonoBehaviour
{
    private IAudioService _audio;

    private void Start()
    {
        ServiceAwaiter.WaitForServices(this, OnReady, OnTimeout);
    }

    private void OnReady()
    {
        _audio = ServiceLocator.Instance.Get<IAudioService>();
    }

    private void OnTimeout()
    {
        Debug.LogError("LoL Engine services did not initialize.");
    }
}

Useful members:

  • WaitForServices(MonoBehaviour monoBehaviour, Action onInitialized)
  • WaitForServices(MonoBehaviour monoBehaviour, Action onInitialized, Action onTimeout, float timeoutSeconds = 10f)
  • AreServicesReady()

CoroutineExtension

LoLEngine.Runtime.CoroutineExtension provides common coroutine helpers.

using LoLEngine.Runtime;
using UnityEngine;

public class DelayedAction : MonoBehaviour
{
    private IEnumerator Start()
    {
        yield return CoroutineExtension.WaitForFrames(3);
        yield return CoroutineExtension.WaitFor(1f);
        yield return CoroutineExtension.WaitForUnscaledTime(0.5f);
    }
}

Useful methods:

  • WaitForFrames(int frameCount)
  • WaitFor(float seconds)
  • WaitForUnscaledTime(float seconds)
  • WaitUntil(Func<bool> condition)
  • WaitWhile(Func<bool> condition)
  • WaitForCancelable(float seconds, Func<bool> cancelCondition)

Singleton Base Classes

The runtime assembly includes three MonoBehaviour singleton bases:

  • Singleton<T> for scene-local singleton components.
  • PersistentSingleton<T> for DontDestroyOnLoad singleton components.
  • RegulatorSingleton<T> for duplicate regulation.

Prefer LoL Engine services for engine systems. Use these bases only for simple game-side MonoBehaviours where the service lifecycle would be unnecessary.

Counter

LoLEngine.Utility.Counter is a small countdown helper that steps with Time.deltaTime and resets when complete.

using LoLEngine.Utility;
using UnityEngine;

public class TickExample : MonoBehaviour
{
    private Counter _counter = new Counter(1f);

    private void Update()
    {
        _counter.Step();

        if (_counter.Done())
        {
            Debug.Log("One second elapsed.");
        }
    }
}

Useful members:

  • Counter(float duration)
  • GetTimeLeft
  • Step()
  • Done()

Model Registry

LoLEngine.Runtime.Models provides an immutable content-model registry.

using LoLEngine.Runtime.Models;

ModelDb.Register(new ModelId("Card", "iron_strike"), new IronStrikeCard());

var id = ModelId.Parse("Card/iron_strike");
var model = ModelDb.Require<IronStrikeCard>(id);

Useful types:

  • ModelId stores IDs as category/entry.
  • AbstractModel enforces canonical vs mutable instance usage.
  • ModelDb registers and resolves canonical models.
  • RegisterInModelDbAttribute can mark model classes for project-side discovery if you build a registrar around it.

LRUCache

LoLEngine.Runtime.Utility.LRUCache<TKey, TValue> is a small least-recently-used cache.

using LoLEngine.Runtime.Utility;

var cache = new LRUCache<string, string>(capacity: 32);
cache.Add("hello", "world");

if (cache.TryGetValue("hello", out var value))
{
    // Use value.
}

Useful members:

  • LRUCache(int capacity)
  • TryGetValue(TKey key, out TValue value)
  • Add(TKey key, TValue value)
  • Clear()

Logging Helpers

LoLEngine.Runtime.Logger includes static logging helpers and sinks.

Common entry points:

  • LoLLogger.Log(...), DebugLog(...), Warning(...), Error(...)
  • GameLogger.Log(...), Warning(...), Error(...)
  • LogChannel
  • LogLevel
  • LoggerConfig
  • HistorySink, UnityConsoleSink, FileSink

For a complete logging walkthrough, see Logger.md.

Color Extensions

LoLEngine.Runtime.Extensions.ColorExtension provides named colors and color helpers.

using LoLEngine.Runtime.Extensions;
using UnityEngine;

Color warning = ColorExtension.Orangered;
string hex = ColorExtension.ColorToHex((Color32)warning);
Color faded = warning.SetAlpha(0.5f);

Useful methods include:

  • Colorize(...)
  • ColorToHex(Color32 color)
  • GetColor(Color32 color)
  • Blend(...)
  • Invert(...)
  • SetAlpha(...)
  • Add(...)
  • Subtract(...)
  • CreateRandomColor(...)

What Is Not Currently Included

Earlier internal docs referenced these helpers, but they are not present in the current package:

  • Helpers/Maths/MathExtension.cs
  • Helpers/Maths/MathfExtension.cs
  • Helpers/Geometry/EdgeHelper.cs
  • Helpers/Extensions/ListExtensions.cs
  • Helpers/Extensions/StringExtension.cs
  • Helpers/Extensions/TimeExtension.cs
  • Helpers/Extensions/VectorExtension.cs
  • Helpers/Extensions/QuaternionExtension.cs
  • Helpers/Extensions/CircularList.cs

Do not rely on those APIs unless you add them in your own project.