Files
Net.Like.Xue.Tokyo/Packages-Local/Com.Project.B.Unity/UX/UXLobbySearch.cs

92 lines
3.2 KiB
C#
Raw Normal View History

2025-06-24 23:49:13 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using BITKit;
using BITKit.Mod;
using BITKit.UX;
using Com.Project.B.Lobby;
using Cysharp.Threading.Tasks;
using Project.B.Player;
using UnityEngine;
using UnityEngine.UIElements;
namespace Project.B.UX
{
public class UXLobbySearch : UIToolKitPanel
{
protected override string DocumentPath=>"ux_lobby_search";
private const string TemplatePath="ux_lobby_search-template";
private VisualTreeAsset _template;
public override bool AllowCursor => true;
public override bool IsWindow => true;
public override bool CloseWhenClickOutside => true;
private readonly ILobbyServices _lobbyServices;
private readonly IUXWaiting _uxWaiting;
private readonly IUXDialogue _dialogue;
private readonly IPlayerData _playerData;
public UXLobbySearch(IUXService uxService, ILobbyServices lobbyServices, IUXWaiting uxWaiting, IPlayerData playerData, IUXDialogue dialogue) : base(uxService)
{
_lobbyServices = lobbyServices;
_uxWaiting = uxWaiting;
_playerData = playerData;
_dialogue = dialogue;
}
[UXBindPath("lobby-container")]
private VisualElement _lobbyContainer;
[UXBindPath("refresh-button")]
private Button _refreshButton;
private CancellationTokenSource _cancellationTokenSource;
public override async UniTask EntryAsync()
{
await base.EntryAsync();
UXUtils.Inject(this);
_template =await ModService.LoadAsset<VisualTreeAsset>(TemplatePath);
_refreshButton.clicked+=()=>Rebuild().Forget();
await Rebuild();
}
private async UniTask Rebuild()
{
try
{
_cancellationTokenSource?.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
var token = _cancellationTokenSource.Token;
_lobbyContainer.Clear();
foreach (var lobbyData in await _lobbyServices.GetAllLobbyDataAsync())
{
if (RootVisualElement is null || token.IsCancellationRequested) return;
var container = _lobbyContainer.Create(_template);
container.Get<Label>().text = lobbyData.Name;
container.Get<Label>(2).text = lobbyData.PlayerIds.Length.ToString();
container.Get<Button>().clicked += () => JoinLobby(lobbyData);
}
}
catch (Exception e)
{
_dialogue.Show(e.Message);
}
}
private async void JoinLobby(ILobbyData lobbyData)
{
var handle = _uxWaiting.Get().SetMessage($"正在加入大厅:{lobbyData.Name}");
try
{
await _lobbyServices.JoinLobbyAsync(_playerData.PlayerId, lobbyData.Id);
UXService.Entry<UXLobby>();
}
catch (Exception e)
{
_dialogue.Show(e.Message);
}
handle.Dispose();
}
}
}