1
This commit is contained in:
83
Src/Unity/Scripts/UX/Popup/UXPopup.cs
Normal file
83
Src/Unity/Scripts/UX/Popup/UXPopup.cs
Normal file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BITKit;
|
||||
using BITKit.UX;
|
||||
using UnityEngine;
|
||||
using UnityEngine.UIElements;
|
||||
|
||||
namespace BITKit.UX
|
||||
{
|
||||
[Serializable]
|
||||
public class UXPopupSelector:IUXPopup
|
||||
{
|
||||
[SerializeReference,SubclassSelector] private IReference popupPath;
|
||||
public void Popup(string content, float duration = 3)
|
||||
{
|
||||
UXPopup.Dictionary[popupPath.Value].Popup(content,duration);
|
||||
}
|
||||
}
|
||||
public sealed class UXPopup : MonoBehaviour,IUXPopup
|
||||
{
|
||||
internal static readonly Dictionary<string,UXPopup> Dictionary=new();
|
||||
|
||||
[SerializeField] private UIDocument document;
|
||||
[SerializeReference, SubclassSelector] private IReference containerPath;
|
||||
[SerializeReference, SubclassSelector] private IReference popupPath;
|
||||
[SerializeField] private VisualTreeAsset popupTemplate;
|
||||
|
||||
private VisualElement container;
|
||||
|
||||
private readonly List<ViewModel> instances = new();
|
||||
|
||||
private class ViewModel
|
||||
{
|
||||
public VisualElement visualElement;
|
||||
public float exitTime;
|
||||
public bool disposed;
|
||||
}
|
||||
|
||||
private void Start()
|
||||
{
|
||||
container = document.rootVisualElement.Q<VisualElement>(containerPath.Value);
|
||||
|
||||
Dictionary.Add(popupPath.Value,this);
|
||||
|
||||
destroyCancellationToken.Register(() => Dictionary.Remove(popupPath.Value));
|
||||
|
||||
container.Clear();
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
foreach (var x in instances.Where(x=>Time.time > x.exitTime))
|
||||
{
|
||||
x.visualElement.RemoveFromHierarchy();
|
||||
x.visualElement.SetOpacity(
|
||||
Mathf.MoveTowards(x.visualElement.GetOpacity(),0,Time.deltaTime)
|
||||
);
|
||||
x.disposed = x.visualElement.GetOpacity() is 0;
|
||||
}
|
||||
instances.RemoveAll(x =>x.disposed);
|
||||
|
||||
container.SetActive(container.childCount > 0);
|
||||
}
|
||||
|
||||
public void Popup(string content, float duration = 3)
|
||||
{
|
||||
var visualElement =new UXContainer(container.Create<VisualElement>(popupTemplate.CloneTree))
|
||||
{
|
||||
contextLabel =
|
||||
{
|
||||
text = content
|
||||
}
|
||||
};
|
||||
instances.Add(new ViewModel()
|
||||
{
|
||||
visualElement = visualElement,
|
||||
exitTime = Time.time + duration
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user