BITFALL/Assets/BITKit/Unity/Scripts/UX/Quest/UXQuest.cs

102 lines
3.3 KiB
C#
Raw Normal View History

2023-06-08 14:09:50 +08:00
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
2023-06-08 14:09:50 +08:00
using UnityEngine;
using BITKit;
using BITKit.SubSystems.Quest;
using UnityEngine.UIElements;
using System.Threading.Tasks;
namespace BITKit.UX
{
public class UXQuest : MonoBehaviour
2023-06-08 14:09:50 +08:00
{
[Header(Constant.Header.Settings)]
public bool clearAfterCompleted;
[Header(Constant.Header.Components)]
[SerializeField] private UIDocument document;
2023-06-08 14:09:50 +08:00
[Header(Constant.Header.Reference)]
[SerializeReference, SubclassSelector] public References completeClassName;
[Header(Constant.Header.Prefabs)]
2023-06-08 14:09:50 +08:00
public VisualTreeAsset visualTreeAsset;
2023-06-08 14:09:50 +08:00
[Header(Constant.Header.InternalVariables)]
private readonly Dictionary<string, UXContainer> dictionary = new();
[UXBindPath("quest-container")]
private VisualElement _container;
private void Start()
2023-06-08 14:09:50 +08:00
{
UXUtils.Inject(this);
2023-06-08 14:09:50 +08:00
QuestSystem.OnQuestCreated += OnQuestCreated;
QuestSystem.OnQuestCompleted += OnQuestCompleted;
QuestSystem.OnQuestCanceled += OnQuestCancened;
_container.Clear();
2023-06-08 14:09:50 +08:00
}
private void OnDestroy()
2023-06-08 14:09:50 +08:00
{
QuestSystem.OnQuestCreated -= OnQuestCreated;
QuestSystem.OnQuestCompleted -= OnQuestCompleted;
QuestSystem.OnQuestCanceled -= OnQuestCancened;
}
private void OnQuestCreated(QuestSystem.Info quest)
2023-06-08 14:09:50 +08:00
{
BIT4Log.Log<UXQuest>($"已创建任务:{quest.name}");
if (dictionary.TryGetValue(quest.name, out var container))
{
container.visualElement.RemoveFromClassList(completeClassName);
}
else
{
container = new(visualTreeAsset.CloneTree());
dictionary.Add(quest.name, container);
}
container.titleLabel.text = quest.name;
container.descriptionLabel.text = quest.description;
_container.Add(container);
2023-06-08 14:09:50 +08:00
}
void OnQuestCancened(QuestSystem.Info quest)
{
BIT4Log.Log<UXQuest>($"已取消任务:{quest.name}");
if (dictionary.TryGetValue(quest.name, out var container))
{
_container.Remove(container);
2023-06-08 14:09:50 +08:00
dictionary.Remove(quest.name);
}
}
async void OnQuestCompleted(QuestSystem.Info quest)
{
BIT4Log.Log<UXQuest>($"已完成任务:{quest.name}");
if (dictionary.TryGetValue(quest.name, out var container))
{
container.visualElement.AddToClassList(completeClassName);
container.titleLabel.text = $"已完成:{quest.name}";
container.visualElement.tabIndex = 256;
if (clearAfterCompleted)
{
dictionary.Remove(quest.name);
try
{
await Task.Delay(8096, destroyCancellationToken);
2023-06-08 14:09:50 +08:00
}
catch (System.OperationCanceledException) { }
catch (System.Exception)
{
_container.Remove(container);
2023-06-08 14:09:50 +08:00
throw;
}
}
}
}
}
}