Add ReplaceResource method to RuntimeGltfInstance

- Enables resource replacement for Texture, Material, AnimationClip, and Mesh
- Provides error handling for null or mismatched types
- Destroys the old resource after replacement
This commit is contained in:
Thomas Moore
2023-08-15 16:24:02 +01:00
parent 89ddfe7386
commit c64ce337f6

View File

@@ -166,6 +166,61 @@ namespace UniGLTF
}
}
public void ReplaceResource(UnityEngine.Object oldResource, UnityEngine.Object newResource)
{
if (oldResource == null || newResource == null || oldResource.GetType() != newResource.GetType())
{
Debug.LogError($"{nameof(RuntimeGltfInstance)} - Could not replace resource: mismatched or null types.");
return;
}
for (int i = 0; i < _resources.Count; i++)
{
if (_resources[i].Item2 == oldResource)
{
_resources[i] = (_resources[i].Item1, newResource);
break;
}
}
switch (oldResource)
{
case Texture oldTexture when newResource is Texture newTexture:
int texIndex = _textures.IndexOf(oldTexture);
if (texIndex != -1)
{
_textures[texIndex] = newTexture;
}
break;
case Material oldMaterial when newResource is Material newMaterial:
int matIndex = _materials.IndexOf(oldMaterial);
if (matIndex != -1)
{
_materials[matIndex] = newMaterial;
}
break;
case AnimationClip oldClip when newResource is AnimationClip newClip:
int clipIndex = _animationClips.IndexOf(oldClip);
if (clipIndex != -1)
{
_animationClips[clipIndex] = newClip;
}
break;
case Mesh oldMesh when newResource is Mesh newMesh:
int meshIndex = _meshes.IndexOf(oldMesh);
if (meshIndex != -1)
{
_meshes[meshIndex] = newMesh;
}
break;
}
Destroy(oldResource);
}
void OnDestroy()
{
Debug.Log("UnityResourceDestroyer.OnDestroy");