Overview
This recipe shows how to make HTTP API calls with local caching for offline fallback. You’ll create anHttpRequestAsset, fetch data asynchronously, cache responses locally via PlayerPrefs, and serve stale cache when the network is unavailable. For a proper cache subsystem with TTL, group tagging, and disk storage, use CacheManager instead of raw PlayerPrefs.
Prerequisites
- SDK modules: Molca Core installed
- Unity setup: RuntimeManager configured in your scene
- Prior knowledge: HttpClient, Dependency injection
- Recommended: Understanding of C# async/await patterns
Step-by-step
Step 1: Create HttpRequest ScriptableObject
Create anHttpRequestAsset to define your API endpoint configuration. This makes the request reusable and configurable in the Inspector.
HttpRequestAsset is a ScriptableObject that encapsulates endpoint configuration (URL, method, headers, body templates). This separates configuration from code and makes it easy to modify endpoints without recompiling.
Step 2: Build the complete caching service
Create a service component that fetches from the API, caches locally, handles staleness, and falls back to cached data on errors.Troubleshooting
- HTTP request fails with “BaseUrl not set”: Configure the
HttpModulein Global Settings with your API base URL. Alternatively, setuseFullUrl = trueon theHttpRequestAssetand provide the complete URL. - JSON parsing fails: Verify that your C# data structure matches the API response format exactly. Field names must match (case-sensitive). Use
[SerializeField]for private fields or make fields public. For complex JSON, consider using Newtonsoft.Json instead ofJsonUtility. - Cached data not persisting between sessions: Ensure you call
PlayerPrefs.Save()after setting values. On some platforms,PlayerPrefsmay not persist immediately without explicit save. For more robust persistence, consider usingDataManagerwith a custom data provider. - Cache never invalidates: Verify that
cacheValiditySecondsis set to a reasonable value. Check that the timestamp is being saved correctly. UseDebug.Logto print cache age and validity checks. - Profile loads but events don’t fire: Ensure
EventDispatcheris injected successfully. Callawait RuntimeManager.WaitForInitialization()before dispatching events. Verify that subscribers are registered before the event is dispatched. - Multiple simultaneous fetches: The
_isFetchingflag prevents concurrent requests. If you need to queue requests, implement a request queue or useDataManager’s built-in queuing.
Related
- HttpClient — async HTTP requests and ScriptableObject endpoints
- DataManager — data providers, caching, and model subscriptions
- Dependency injection — injecting HttpClient and DataManager services
- EventDispatcher — notifying other systems when data is loaded
- Recipe: Create and dispatch custom events — using EventDispatcher for notifications