MiniGame-PushPush/Assets/Scripts/Addressable/AddressableManager.cs

120 lines
3.3 KiB
C#
Raw Normal View History

2023-10-04 20:20:04 +09:00
using FirstVillain.Singleton;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Events;
2023-10-04 20:20:04 +09:00
using UnityEngine.Pool;
using UnityEngine.ResourceManagement.AsyncOperations;
2023-10-04 20:20:04 +09:00
public class AddressableManager : UnitySingleton<AddressableManager>
{
[SerializeField] private Transform _objectPoolRoot;
2023-10-04 20:20:04 +09:00
private bool _collectionCheck = false;
private int _maxPoolSize = 100;
private Dictionary<string, ObjectPool<GameObject>> _objectPoolDict = new();
protected override void AwakeSingleton()
{
base.AwakeSingleton();
Addressables.InitializeAsync();
}
public T LoadAssetAsync<T>(string name) where T : UnityEngine.Object
2023-10-04 20:20:04 +09:00
{
var handle = Addressables.LoadAssetAsync<T>(name);
var result = handle.WaitForCompletion();
Addressables.Release(handle);
return result;
2023-10-04 20:20:04 +09:00
}
public GameObject Spawn(string name, Transform parent)
2023-10-04 20:20:04 +09:00
{
if(!_objectPoolDict.ContainsKey(name))
2023-10-04 20:20:04 +09:00
{
var loaded = LoadAssetAsync<GameObject>(name);
_objectPoolDict.Add(name, CreateNewObjectPool(loaded, name));
2023-10-04 20:20:04 +09:00
}
GameObject obj;
obj = _objectPoolDict[name].Get();
obj.transform.SetParent(parent);
return obj;
2023-10-04 20:20:04 +09:00
}
2023-10-04 20:20:04 +09:00
public void Release(GameObject obj)
{
if (_objectPoolDict.ContainsKey(obj.name))
{
try
{
obj.transform.parent = null;
2023-10-04 20:20:04 +09:00
try
{
_objectPoolDict[obj.name].Release(obj);
}
catch
{
obj.SetActive(false);
}
}
catch (Exception ex)
{
Debug.LogError($"Exception has occured!!! Object : {obj.name} === {ex.Message}");
}
}
else
{
Debug.LogWarning($"Object[{obj.name}] does not exist in pool dictionary. But it's been destroyed anyway :D");
Destroy(obj);
}
}
public void ReleaseAll()
{
foreach (var pool in _objectPoolDict)
{
pool.Value.Dispose();
}
_objectPoolDict.Clear();
}
2023-10-04 20:20:04 +09:00
private ObjectPool<GameObject> CreateNewObjectPool(GameObject prefab, string resourceName)
{
return new ObjectPool<GameObject>(
() =>
{
GameObject obj = Instantiate(prefab);
obj.name = resourceName;
return obj;
},
OnGetFromPoolActive,
OnReleasedToPool,
OnDestroyPoolObject,
_collectionCheck /* Collection checks will throw errors if we try to release an item that is already in the pool.*/,
10/*defalut capacity*/,
_maxPoolSize
);
}
private void OnGetFromPoolInActive(GameObject obj)
{
obj.SetActive(false);
}
private void OnGetFromPoolActive(GameObject obj)
{
obj.SetActive(true);
}
private void OnReleasedToPool(GameObject obj)
{
obj.SetActive(false);
}
private void OnDestroyPoolObject(GameObject obj)
{
Destroy(obj);
}
}