using System;
using System.Collections.Generic;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceLocations;
using UnityEngine.ResourceManagement.Util;
using UnityEngine.SceneManagement;
namespace UnityEngine.ResourceManagement.ResourceProviders
{
///
/// Basic implementation of IInstanceProvider.
///
public class InstanceProvider : IInstanceProvider
{
Dictionary> m_InstanceObjectToPrefabHandle = new Dictionary>();
///
/// Provide an instance of a loaded GameObject
///
/// The resource manager to use
/// The operation handle with a reference to the object to instantiate
/// Container for data to specficy how to instantiate
/// The instance GameObject
public GameObject ProvideInstance(ResourceManager resourceManager, AsyncOperationHandle prefabHandle, InstantiationParameters instantiateParameters)
{
GameObject result = instantiateParameters.Instantiate(prefabHandle.Result);
m_InstanceObjectToPrefabHandle.Add(result, prefabHandle);
return result;
}
///
/// Destroy the instance and release one ref count on the operaiton handle
///
/// The resource manager used to instantiate the GameObject
/// The instance GameObject to destroy
public void ReleaseInstance(ResourceManager resourceManager, GameObject instance)
{
// Guard for null - note that Unity overloads equality for GameObject so `default(GameObject) == null` is true so must use explicit `is null` type guard
if (instance is null)
return;
AsyncOperationHandle resource;
if (!m_InstanceObjectToPrefabHandle.TryGetValue(instance, out resource))
{
Debug.LogWarningFormat("Releasing unknown GameObject {0} to InstanceProvider.", instance);
}
else
{
resource.Release();
m_InstanceObjectToPrefabHandle.Remove(instance);
}
if (instance != null)
{
if (Application.isPlaying)
Object.Destroy(instance);
else
Object.DestroyImmediate(instance);
}
}
}
}