BITFALL/Assets/Artists/Scripts/UX/UXSurvival.cs

64 lines
1.9 KiB
C#

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using BITFALL.Player.Survival;
using BITKit.Entities;
using BITKit.Entities.Player;
using BITKit.UX;
using RotaryHeart.Lib.SerializableDictionary;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
namespace BITFALL.UX
{
public class UXSurvival : MonoBehaviour
{
[SerializeReference,SubclassSelector] private IPlayerService playerService;
[SerializeField] private SerializableDictionaryBase<string,Sprite> survivalEventIcons;
[SerializeField] private UXBuilder survivalEventBuilder;
private readonly ConcurrentDictionary<string,UXContainer> spawnedSurvivalEvents = new();
private IPlayerSurvival _playerSurvival;
private void Awake()
{
playerService.OnPlayerInitialized += OnPlayerInitialized;
}
private void OnDestroy()
{
playerService.OnPlayerInitialized -= OnPlayerInitialized;
}
private void OnPlayerInitialized(Entity obj)
{
_playerSurvival = obj.Get<IPlayerSurvival>();
_playerSurvival.OnSurvivalEventOpened += OnSurvivalEventOpened;
_playerSurvival.OnSurvivalEventClosed += OnSurvivalEventClosed;
}
private void OnSurvivalEventClosed(IPlayerSurvivalEvent obj)
{
if (spawnedSurvivalEvents.TryRemove(obj.GetType().Name, out var container))
{
container.visualElement.RemoveFromHierarchy();
}
}
private void OnSurvivalEventOpened(IPlayerSurvivalEvent obj)
{
spawnedSurvivalEvents.GetOrAdd(obj.GetType().Name, (x)=>Create(obj));
}
private UXContainer Create(IPlayerSurvivalEvent playerSurvivalEvent)
{
var container = survivalEventBuilder.BuildAsContainer();
var key = playerSurvivalEvent.GetType().Name;
if (survivalEventIcons.TryGetValue(key, out var sprite))
{
container.icon.style.backgroundImage = new StyleBackground(sprite);
}
container.contextLabel.text = playerSurvivalEvent.Title;
return container;
}
}
}