Skip to main content

Requester

Important Attention Reminder

Coding Style wiki


Requester is a resource requester based on UniTask + UnityWebRequest, supporting web/file requests for AudioClip, Texture2D, Sprite, byte[], and string, with optional ARC or LRU caching (keyed by URL), plus timeout (180 seconds by default) and cancellation (CancellationTokenSource) mechanisms. On failure, an ErrorInfo is delivered through errorAction.

NamespaceOxGKit.Utilities.Requester
Typepublic class Requester, public struct ErrorInfo
SourceRequester.cs
using Cysharp.Threading.Tasks;
using OxGKit.Utilities.Requester;

Attention The static methods listed on this page operate through an internal lazy singleton; every method also has a Self-prefixed instance counterpart (e.g. SelfRequestTexture2D), so you can new Requester() to create an instance with an isolated cache scope (see Static vs. Instance Calls).

Quick Start

using Cysharp.Threading.Tasks;
using OxGKit.Utilities.Requester;
using System.Threading;
using UnityEngine;

// Initialize the cache capacity per resource type at boot (choose ARC or LRU)
Requester.InitARCCacheCapacityForAudio(20);
Requester.InitARCCacheCapacityForTexture2d(60);
Requester.InitARCCacheCapacityForText(100);

// Request a Texture2D (cached with the URL as key when cached = true)
Texture2D t2d = await Requester.RequestTexture2D
(
url,
(texture) => Debug.Log($"Loaded: {texture.width}x{texture.height}"),
(error) => Debug.Log($"Error: {error.message}")
);

// Request an AudioClip (specify the correct AudioType)
AudioClip clip = await Requester.RequestAudio(url, AudioType.OGGVORBIS);

// Bind the request lifetime with a CancellationTokenSource
var cts = new CancellationTokenSource();
string text = await Requester.RequestText(url, null, null, cts);
// Cancel the request when the owner is destroyed
cts.Cancel();

General Rules

Static vs. Instance Calls (Self Series)

Every static method of Requester has a Self-prefixed instance counterpart (RequestTexture2DSelfRequestTexture2D, InitLRUCacheCapacityForTextSelfInitLRUCacheCapacityForText, etc.) with identical parameters and behavior — the only difference is the cache scope:

  • Static calls: operate through an internal singleton, so the whole project shares one set of global caches. Use this for most scenarios.
  • Instance calls (via new): create your own instance with new Requester() and call the Self* methods on it — that instance owns a fully isolated cache scope (capacity settings, clearing, and releasing never affect others). Ideal when a specific feature needs to manage its own cache lifecycle (e.g. chat avatars or event-page images that get released in one batch on exit).
using OxGKit.Utilities.Requester;

// Static call (global shared caches)
var tex = await Requester.RequestTexture2D(url);

// Instance call (via new, with an isolated cache scope)
var chatRequester = new Requester();

// Initialize an independent LRU cache capacity for this instance
chatRequester.SelfInitLRUCacheCapacityForTexture2d(30);

// Request through the Self method (cached only inside this instance)
var avatar = await chatRequester.SelfRequestTexture2D(avatarUrl);

// Release this instance's caches in one batch on exit (global caches unaffected)
chatRequester.SelfRelease();

Reminder The following sections list the static signatures; every method has an identically named Self instance version — just add the Self prefix to call it on an instance.

Caching

  • Caches are keyed by URL; on a hit, the value is returned immediately and successAction is invoked (no request is sent).
  • Each resource type (Audio / Texture2d / Text) allows only one cache strategy: initializing ARC clears and disables LRU for that type, and vice versa.
  • If no cache has been initialized, the cached parameter has no effect (nothing is cached).
  • RequestBytes has no caching (every call sends a new request).

Reminder RequestSprite caches the underlying Texture2D only; the Sprite itself is recreated with Sprite.Create on every call. Hold on to the created Sprite yourself when using it frequently.

Attention Calling an Init method again clears and recreates the cache for that type (cached entries go through eviction handling). Initialize once at boot.

Timeout and Cancellation

  • Without cts: an internal CancellationTokenSource is created and timeoutSeconds is applied (defaults to 180 seconds when unspecified) as a timeout guard.
  • With a custom cts: timeoutSeconds has no effect; cancellation timing is fully controlled by the caller.

Important When the object holding the request result is destroyed, remember to call cts.Cancel() to cancel in-flight requests; otherwise callbacks may fire into released objects.

Error Handling

  • When the URL is null or empty, the request fails (ConnectionError / ProtocolError / DataProcessingError), or an exception occurs, errorAction receives an ErrorInfo and the return value is null (default).
  • Errors are also logged through OxGKit.LoggingSystem (logger name OxGKit.Utilities.Logger).

ErrorInfo

public struct ErrorInfo
{
public string url;
public string message;
public Exception exception;
}

The error information delivered through errorAction when a request fails.

MemberDescription
urlThe requested URL (null when the URL is missing).
messageThe error message (UnityWebRequest.error).
exceptionThe exception (null for non-exception errors).

Request Methods

Method Overview

Method (static)Self Instance Version (via new)Description
RequestAudioSelfRequestAudioRequests an AudioClip (cacheable).
RequestTexture2DSelfRequestTexture2DRequests a Texture2D (cacheable).
RequestSpriteSelfRequestSpriteRequests and creates a Sprite (caches the underlying Texture2D).
RequestBytesSelfRequestBytesRequests file bytes (no caching).
RequestTextSelfRequestTextRequests text content (cacheable).

RequestAudio

public static async UniTask<AudioClip> RequestAudio(string url, AudioType audioType = AudioType.MPEG, Action<AudioClip> successAction = null, Action<ErrorInfo> errorAction = null, CancellationTokenSource cts = null, bool cached = true, int? timeoutSeconds = null)

Requests an AudioClip (streamed download). Specify the audioType matching the audio file format (defaults to AudioType.MPEG).

AudioClip clip = await Requester.RequestAudio
(
"https://example.com/audio.ogg",
AudioType.OGGVORBIS,
(audioClip) => audioSource.PlayOneShot(audioClip),
(error) => Debug.Log($"Error: {error.message}")
);

Attention A mismatched audioType causes decoding failures; WebGL has platform limits on streaming audio, so verify the supported formats there.

RequestTexture2D

public static async UniTask<Texture2D> RequestTexture2D(string url, Action<Texture2D> successAction = null, Action<ErrorInfo> errorAction = null, CancellationTokenSource cts = null, bool cached = true, int? timeoutSeconds = null)

Requests a Texture2D. With cached = true and an initialized cache, a second request for the same URL returns the cached value directly.

Texture2D t2d = await Requester.RequestTexture2D
(
"https://example.com/image.png",
(texture) => rawImage.texture = texture
);

RequestSprite

public static async UniTask<Sprite> RequestSprite(string url, Action<Sprite> successAction = null, Action<ErrorInfo> errorAction = null, Vector2 position = default, Vector2 pivot = default, float pixelPerUnit = 100, uint extrude = 0, SpriteMeshType meshType = SpriteMeshType.FullRect, CancellationTokenSource cts = null, bool cached = true, int? timeoutSeconds = null)

Requests a Texture2D and returns a Sprite created via Sprite.Create; when pivot is unspecified (Vector2.zero), the center (0.5f, 0.5f) is applied automatically.

Sprite sprite = await Requester.RequestSprite
(
"https://example.com/icon.png",
(sp) => image.sprite = sp
);

RequestBytes

public static async UniTask<byte[]> RequestBytes(string url, Action<byte[]> successAction = null, Action<ErrorInfo> errorAction = null, CancellationTokenSource cts = null, int? timeoutSeconds = null)

Requests the byte[] content of a file. No caching (there is no cached parameter).

byte[] bytes = await Requester.RequestBytes("https://example.com/file.bin");

RequestText

public static async UniTask<string> RequestText(string url, Action<string> successAction = null, Action<ErrorInfo> errorAction = null, CancellationTokenSource cts = null, bool cached = true, int? timeoutSeconds = null)

Requests text content (string). With cached = true and an initialized cache, the result is cached with the URL as key.

string json = await Requester.RequestText("https://example.com/config.json");

Cache Management

Method Overview

Method (static)Self Instance Version (via new)Description
InitARCCacheCapacityFor...SelfInitARCCacheCapacityFor...Initializes the ARC cache capacity for a resource type (disables that type's LRU cache).
InitLRUCacheCapacityFor...SelfInitLRUCacheCapacityFor...Initializes the LRU cache capacity for a resource type (disables that type's ARC cache).
RemoveFromARCCacheFor...SelfRemoveFromARCCacheFor...Removes a URL from a resource type's ARC cache.
RemoveFromLRUCacheFor...SelfRemoveFromLRUCacheFor...Removes a URL from a resource type's LRU cache.
ClearARCCacheCapacityFor...SelfClearARCCacheCapacityFor...Clears a resource type's ARC cache.
ClearLRUCacheCapacityFor...SelfClearLRUCacheCapacityFor...Clears a resource type's LRU cache.
AutoRemoveFromCachesSelfAutoRemoveFromCachesSearches all caches and removes the given URL.
ClearAllCachesSelfClearAllCachesClears all caches.
ReleaseSelfReleaseClears and releases all cache containers.

InitARCCacheCapacityFor...

public static void InitARCCacheCapacityForAudio(int capacity = 20)

public static void InitARCCacheCapacityForTexture2d(int capacity = 60)

public static void InitARCCacheCapacityForText(int capacity = 100)

Initializes the ARC cache capacity for the given resource type; since each type allows only one cache strategy, this clears and disables that type's LRU cache.

Requester.InitARCCacheCapacityForTexture2d(60);

InitLRUCacheCapacityFor...

public static void InitLRUCacheCapacityForAudio(int capacity = 20)

public static void InitLRUCacheCapacityForTexture2d(int capacity = 60)

public static void InitLRUCacheCapacityForText(int capacity = 80)

Initializes the LRU cache capacity for the given resource type; this clears and disables that type's ARC cache.

Requester.InitLRUCacheCapacityForTexture2d(60);

RemoveFromARCCacheFor...

public static bool RemoveFromARCCacheForAudio(string url)

public static bool RemoveFromARCCacheForTexture2d(string url)

public static bool RemoveFromARCCacheForText(string url)

Removes a URL entry from the given resource type's ARC cache; returns true on success.

RemoveFromLRUCacheFor...

public static bool RemoveFromLRUCacheForAudio(string url)

public static bool RemoveFromLRUCacheForTexture2d(string url)

public static bool RemoveFromLRUCacheForText(string url)

Removes a URL entry from the given resource type's LRU cache; returns true on success.

ClearARCCacheCapacityFor...

public static void ClearARCCacheCapacityForAudio()

public static void ClearARCCacheCapacityForTexture2d()

public static void ClearARCCacheCapacityForText()

Clears the given resource type's ARC cache (invoking eviction handling per entry).

ClearLRUCacheCapacityFor...

public static void ClearLRUCacheCapacityForAudio()

public static void ClearLRUCacheCapacityForTexture2d()

public static void ClearLRUCacheCapacityForText()

Clears the given resource type's LRU cache (invoking eviction handling per entry).

AutoRemoveFromCaches

public static bool AutoRemoveFromCaches(string url)

Searches all caches (ARC and LRU for Audio / Texture2d / Text), removes the given URL when found, and returns true.

Requester.AutoRemoveFromCaches(url);

ClearAllCaches

public static void ClearAllCaches()

Clears all initialized caches (ARC and LRU for Audio / Texture2d / Text).

Release

public static void Release()

Clears all caches and releases the cache containers (sets them to null); call an Init method again to restore caching.

Reminder Cached Unity objects (AudioClip / Texture2D) are automatically destroyed on eviction or removal (see Cacher); objects requested with cached = false must be destroyed by the caller when no longer needed.