using System.Collections.Generic;
using UnityEngine;
namespace TriLibCore
{
/// Represents a Class to destroy every Asset (Textures, Materials, Meshes) loaded by TriLib for this GameObject.
public class AssetUnloader : MonoBehaviour
{
///
/// Assets Allocation List.
///
public List Allocations;
/// The Asset Unloader unique identifier.
public int Id
{
get => _id;
set
{
_id = value;
Register();
}
}
///
/// Custom data used to load the model.
///
public object CustomData;
[SerializeField]
[HideInInspector]
private int _id;
private static int _lastId;
private static readonly Dictionary AssetUnloaders = new Dictionary();
/// Gets the next allocation Identifier.
/// The Allocation Identifier.
public static int GetNextId()
{
return _lastId++;
}
///
/// Returns whether there is any AssetUnloader instance active.
///
public static bool HasRegisteredUnloaders
{
get
{
return AssetUnloaders.Count > 0;
}
}
private void Register()
{
if (!AssetUnloaders.ContainsKey(_id))
{
AssetUnloaders[_id] = 0;
}
else
{
AssetUnloaders[_id]++;
}
}
private void Start()
{
Register();
}
private void OnDestroy()
{
if (AssetUnloaders.TryGetValue(_id, out var value))
{
if (--value <= 0)
{
for (var i = 0; i < Allocations.Count; i++)
{
var allocation = Allocations[i];
if (allocation == null)
{
continue;
}
Destroy(allocation);
}
AssetUnloaders.Remove(_id);
}
else
{
AssetUnloaders[_id] = value;
}
}
}
}
}