Requester
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.
| Namespace | OxGKit.Utilities.Requester |
| Type | public class Requester, public struct ErrorInfo |
| Source | Requester.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 (RequestTexture2D ↔ SelfRequestTexture2D, InitLRUCacheCapacityForText ↔ SelfInitLRUCacheCapacityForText, 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 withnew Requester()and call theSelf*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
successActionis 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
cachedparameter 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 internalCancellationTokenSourceis created andtimeoutSecondsis applied (defaults to 180 seconds when unspecified) as a timeout guard. - With a custom
cts:timeoutSecondshas 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,
errorActionreceives an ErrorInfo and the return value isnull(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.
| Member | Description |
|---|---|
url | The requested URL (null when the URL is missing). |
message | The error message (UnityWebRequest.error). |
exception | The exception (null for non-exception errors). |
Request Methods
Method Overview
| Method (static) | Self Instance Version (via new) | Description |
|---|---|---|
| RequestAudio | SelfRequestAudio | Requests an AudioClip (cacheable). |
| RequestTexture2D | SelfRequestTexture2D | Requests a Texture2D (cacheable). |
| RequestSprite | SelfRequestSprite | Requests and creates a Sprite (caches the underlying Texture2D). |
| RequestBytes | SelfRequestBytes | Requests file bytes (no caching). |
| RequestText | SelfRequestText | Requests 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. |
| AutoRemoveFromCaches | SelfAutoRemoveFromCaches | Searches all caches and removes the given URL. |
| ClearAllCaches | SelfClearAllCaches | Clears all caches. |
| Release | SelfRelease | Clears 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.