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

89 lines
2.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BITFALL.Cosmetic;
using BITKit;
using BITKit.IO;
using BITKit.Modification;
using BITKit.UX;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UIElements;
using YooAsset;
namespace BITFALL.UX
{
public class UXCosmetics : MonoBehaviour
{
[SerializeReference,SubclassSelector] private ICosmeticService _cosmeticService;
[SerializeField] private VisualTreeAsset cosmeticsTemplate;
[UXBindPath("cosmetics-container")]
private VisualElement _cosmeticsContainer;
private void Start()
{
BITKit.UX.UXUtils.Inject(this);
_cosmeticsContainer.Clear();
_cosmeticService.OnCosmeticsChanged += Rebuild;
Rebuild();
}
private void Rebuild()
{
_cosmeticsContainer.Clear();
var modified = _cosmeticService.Modified.Values.ToArray();
foreach (var cosmetic in _cosmeticService.Cosmetics)
{
var assetHandle = YooAssets.LoadAssetAsync(cosmetic.AddressablePath);
assetHandle.WaitForAsyncComplete();
if(destroyCancellationToken.IsCancellationRequested) return;
var so = assetHandle.AssetObject.As<AssetableCosmetic>();
var instance =new UXContainer(_cosmeticsContainer.Create(cosmeticsTemplate)) ;
instance.icon.style.backgroundImage = new StyleBackground(so.Icon);
instance.contextLabel.text = so.name;
var inUsed = modified.Contains(cosmetic);
if(inUsed)
{
instance.visualElement.AddToClassList("--toggled");
}
instance.button.clicked += () =>
{
try
{
if (inUsed)
{
_cosmeticService.Remove(so.Type, out _);
}
else
{
_cosmeticService.Add(so.Type, cosmetic);
}
}
catch (NotRequireModifyException e)
{
Alert.Print("需要前置", e.Message);
}
catch (IncompatibleModifyException e)
{
Alert.Print("不兼容的修改", e.Message);
}
catch (NotSupportModifyException e)
{
Alert.Print("不支持的修改", e.Message);
}
};
}
}
}
}