ProjectDDD/Assets/_DDD/_Scripts/RestaurantState/FlowStates/RestaurantCustomerState.cs

99 lines
3.6 KiB
C#

using System.Collections.Generic;
using System.Threading.Tasks;
using Opsive.BehaviorDesigner.Runtime;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace DDD
{
public class RestaurantCustomerState : ScriptableObject
{
private Dictionary<CustomerType, Subtree> _loadedSubtrees = new();
private Dictionary<CustomerType, AssetReference> _subtreeAssetReference = new();
public async Task LoadCustomerBehaviorData()
{
var customerData = RestaurantData.Instance?.CustomerData;
if (customerData?.CustomerBehaviorData == null)
{
Debug.LogError("[RestaurantCustomerState] RestaurantCustomerData or CustomerBehaviorData is null");
return;
}
var loadTasks = new List<Task>();
foreach (var behaviorPair in customerData.CustomerBehaviorData)
{
var customerType = behaviorPair.Key;
var subtreeReference = behaviorPair.Value;
if (_loadedSubtrees.ContainsKey(customerType))
continue; // Already loaded
loadTasks.Add(LoadSubtreeAsync(customerType, subtreeReference));
}
await Task.WhenAll(loadTasks);
Debug.Log($"[RestaurantCustomerState] Loaded {_loadedSubtrees.Count} customer behavior subtrees");
}
private async Task LoadSubtreeAsync(CustomerType customerType, AssetReference subtreeReference)
{
var subtree = await AssetManager.Instance.LoadAssetAsync<Subtree>(subtreeReference);
if (subtree != null)
{
_loadedSubtrees[customerType] = subtree;
_subtreeAssetReference[customerType] = subtreeReference;
Debug.Log($"[RestaurantCustomerState] Loaded subtree for {customerType}");
}
else
{
Debug.LogError($"[RestaurantCustomerState] Failed to load subtree for {customerType}");
}
}
public void UnloadCustomerBehaviorData()
{
foreach (var assetReference in _subtreeAssetReference.Values)
{
AssetManager.Instance.ReleaseAsset(assetReference);
}
_loadedSubtrees.Clear();
_subtreeAssetReference.Clear();
Debug.Log("[RestaurantCustomerState] Unloaded all customer behavior subtrees");
}
public Subtree GetLoadedSubtree(CustomerType customerType)
{
_loadedSubtrees.TryGetValue(customerType, out var subtree);
return subtree;
}
public async Task<Subtree> GetOrLoadSubtree(CustomerType customerType)
{
if (IsSubtreeLoaded(customerType))
{
return GetLoadedSubtree(customerType);
}
else
{
var customerData = RestaurantData.Instance?.CustomerData;
if (customerData?.CustomerBehaviorData == null ||
!customerData.CustomerBehaviorData.TryGetValue(customerType, out var subtreeReference))
{
Debug.LogError($"[RestaurantCustomerState] No behavior data found for {customerType}");
return null;
}
await LoadSubtreeAsync(customerType, subtreeReference);
return GetLoadedSubtree(customerType);
}
}
public bool IsSubtreeLoaded(CustomerType customerType)
{
return _loadedSubtrees.ContainsKey(customerType);
}
}
}