To implement a loading indicator while fetching high-res textures for Spine in Unity, you can indeed use the TextureRequested
and TextureLoaded
delegates. These delegates can help you manage the loading state for multiple textures. Here’s a general approach to achieve this:
Subscribe to Delegates: Subscribe to the TextureRequested
and TextureLoaded
delegates to show and hide the loading indicator.
Track Loading State: Maintain a counter or a list to track the number of textures being loaded. Increment the counter when a texture is requested and decrement it when a texture is loaded.
Show/Hide Loading Indicator: Show the loading indicator when the counter is greater than zero and hide it when the counter reaches zero.
Handle Failures: Implement a timeout or error handling mechanism to hide the loading indicator if a texture fails to load.
Here’s a sample implementation:
using UnityEngine;
using Spine.Unity;
public class SpineTextureLoader : MonoBehaviour
{
public SkeletonRenderer skeletonRenderer;
public GameObject loadingIndicator;
private int texturesLoading = 0;
void OnEnable()
{
OnDemandTextureLoader loader = skeletonRenderer.SkeletonDataAsset.atlasAssets[0].OnDemandTextureLoader;
loader.TextureRequested += HandleTextureRequested;
loader.TextureLoaded += HandleTextureLoaded;
}
void OnDisable()
{
OnDemandTextureLoader loader = skeletonRenderer.SkeletonDataAsset.atlasAssets[0].OnDemandTextureLoader;
loader.TextureRequested -= HandleTextureRequested;
loader.TextureLoaded -= HandleTextureLoaded;
}
private void HandleTextureRequested(OnDemandTextureLoader loader, Material material, int textureIndex)
{
texturesLoading++;
UpdateLoadingIndicator();
}
private void HandleTextureLoaded(OnDemandTextureLoader loader, Material material, int textureIndex)
{
texturesLoading--;
UpdateLoadingIndicator();
}
private void UpdateLoadingIndicator()
{
loadingIndicator.SetActive(texturesLoading > 0);
}
private void HandleTextureLoadFailed()
{
// Implement your error handling logic here
texturesLoading = Mathf.Max(0, texturesLoading - 1);
UpdateLoadingIndicator();
}
}
Handling Failures
To handle failed cases, you can implement a timeout mechanism or listen for error events if available. For example, you can start a coroutine when a texture is requested and stop it when the texture is loaded. If the coroutine times out, you can assume the texture load failed and update the loading indicator accordingly.
private IEnumerator TextureLoadTimeout(float timeout)
{
yield return new WaitForSeconds(timeout);
if (texturesLoading > 0)
{
HandleTextureLoadFailed();
}
}
Summary
You can use the TextureRequested
and TextureLoaded
delegates to manage a loading indicator for multiple textures. Track the number of textures being loaded and update the indicator accordingly. Implement a timeout or error handling mechanism to handle failed texture loads.