138 lines
3.5 KiB
C#
138 lines
3.5 KiB
C#
using TMPro;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
namespace FloodSWE.Networking
|
|
{
|
|
/// <summary>
|
|
/// Drives a Connect/Disconnect button from SweQuestControlClient state.
|
|
/// </summary>
|
|
public sealed class SweConnectionButtonController : MonoBehaviour
|
|
{
|
|
[Header("References")]
|
|
[SerializeField] private SweQuestControlClient controlClient;
|
|
[SerializeField] private Button button;
|
|
[SerializeField] private TMP_Text label;
|
|
|
|
[Header("Labels")]
|
|
[SerializeField] private string connectLabel = "Connect";
|
|
[SerializeField] private string loadingLabel = "Loading...";
|
|
[SerializeField] private string disconnectLabel = "Disconnect";
|
|
|
|
[Header("Behavior")]
|
|
[SerializeField] private bool disableButtonWhileLoading = true;
|
|
[SerializeField] private bool allowCancelWhileLoading = false;
|
|
|
|
private void OnEnable()
|
|
{
|
|
if (button == null)
|
|
{
|
|
button = GetComponent<Button>();
|
|
}
|
|
|
|
if (label == null && button != null)
|
|
{
|
|
label = button.GetComponentInChildren<TMP_Text>();
|
|
}
|
|
|
|
if (controlClient == null)
|
|
{
|
|
controlClient = FindFirstObjectByType<SweQuestControlClient>();
|
|
}
|
|
|
|
if (button != null)
|
|
{
|
|
button.onClick.AddListener(OnButtonPressed);
|
|
}
|
|
|
|
RefreshVisual();
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
if (button != null)
|
|
{
|
|
button.onClick.RemoveListener(OnButtonPressed);
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
RefreshVisual();
|
|
}
|
|
|
|
public void OnButtonPressed()
|
|
{
|
|
if (controlClient == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (controlClient.IsConnectionAlive)
|
|
{
|
|
controlClient.Disconnect();
|
|
return;
|
|
}
|
|
|
|
if (controlClient.IsWaitingForAck)
|
|
{
|
|
if (allowCancelWhileLoading)
|
|
{
|
|
controlClient.Disconnect();
|
|
}
|
|
return;
|
|
}
|
|
|
|
controlClient.Connect();
|
|
}
|
|
|
|
private void RefreshVisual()
|
|
{
|
|
if (controlClient == null)
|
|
{
|
|
SetLabel(connectLabel);
|
|
SetButtonInteractable(false);
|
|
return;
|
|
}
|
|
|
|
if (controlClient.IsConnectionAlive)
|
|
{
|
|
SetLabel(disconnectLabel);
|
|
SetButtonInteractable(true);
|
|
return;
|
|
}
|
|
|
|
if (controlClient.IsWaitingForAck)
|
|
{
|
|
SetLabel(loadingLabel);
|
|
bool interactable = !disableButtonWhileLoading || allowCancelWhileLoading;
|
|
SetButtonInteractable(interactable);
|
|
return;
|
|
}
|
|
|
|
SetLabel(connectLabel);
|
|
SetButtonInteractable(true);
|
|
}
|
|
|
|
private void SetLabel(string textValue)
|
|
{
|
|
if (label == null || label.text == textValue)
|
|
{
|
|
return;
|
|
}
|
|
|
|
label.text = textValue;
|
|
}
|
|
|
|
private void SetButtonInteractable(bool interactable)
|
|
{
|
|
if (button == null || button.interactable == interactable)
|
|
{
|
|
return;
|
|
}
|
|
|
|
button.interactable = interactable;
|
|
}
|
|
}
|
|
}
|