using System.Collections.Generic;
using Godot;
namespace ColdMint.scripts.utils;
///
/// UI Group
/// UI组
///
public partial class UiGroup : Control
{
private readonly HashSet _visibleControls = [];
private readonly HashSet _allControls = [];
///
/// How many nodes are visible
/// 有多少个节点处于可见状态
///
public int VisibleControlsCount => _visibleControls.Count;
///
/// Register nodes in the UI group. For registered nodes, do not use or to change the visible state. Call the and methods instead.
/// 注册节点到UI组内,对于已注册的节点,不要直接使用或方法来改变可见状态,请调用和方法来替代他们。
///
///
public void RegisterControl(Control control)
{
control.TreeExited += () => { OnTreeExited(control); };
NodeUtils.CallDeferredAddChild(this, control);
_allControls.Add(control);
}
///
/// Hide all nodes
/// 隐藏全部节点
///
public void HideAllControl()
{
if (_visibleControls.Count == 0)
{
return;
}
foreach (var visibleControl in _visibleControls)
{
visibleControl.Hide();
}
_visibleControls.Clear();
Hide();
}
///
/// Hide a node
/// 隐藏某个节点
///
///
///
public bool HideControl(Control control)
{
if (!control.IsVisible())
{
return false;
}
if (!_allControls.Contains(control))
{
return false;
}
control.Hide();
_visibleControls.Remove(control);
ChangeSelfVisibility();
return true;
}
///
/// Show node
/// 显示某个节点
///
///
///
public bool ShowControl(Control control)
{
if (control.IsVisible())
{
return false;
}
if (!_allControls.Contains(control))
{
return false;
}
control.Show();
_visibleControls.Add(control);
ChangeSelfVisibility();
return true;
}
///
/// ChangeSelfVisibility
/// 改变自身的可见度
///
private void ChangeSelfVisibility()
{
if (_visibleControls.Count == 0)
{
Hide();
}
else
{
Show();
}
}
private void OnTreeExited(Control control)
{
//The Hide method is not called when a node exits from the tree, so remove the node here to prevent empty references.
//当节点从节点树内退出时,并不会调用Hide方法,所以在这里移除节点,防止产生空引用。
_visibleControls.Remove(control);
_allControls.Remove(control);
}
}