using UnityEngine;
using UnityEngine.UI;
///
/// GraphicRaycaster 管理器,负责管理UI的射线检测功能
/// 使用组合模式,从UIWindow中提取出GraphicRaycaster管理功能
///
public class GraphicRaycasterManager
{
private GameObject _rootGameObject;
private int _disableGraphicRaycasterCount;
///
/// 构造函数
///
/// 需要管理GraphicRaycaster的根GameObject
public GraphicRaycasterManager(GameObject rootGameObject)
{
_rootGameObject = rootGameObject;
_disableGraphicRaycasterCount = 0;
}
///
/// 是否启用GraphicRaycaster
///
public bool IsEnableGraphicRaycaster
{
get { return _disableGraphicRaycasterCount <= 0; }
set
{
if (value)
{
if (_disableGraphicRaycasterCount > 0)
--_disableGraphicRaycasterCount;
}
else
++_disableGraphicRaycasterCount;
if (null == _rootGameObject)
return;
UpdateGraphicRaycasterState();
}
}
///
/// 更新GraphicRaycaster状态
///
private void UpdateGraphicRaycasterState()
{
bool isEnabled = _disableGraphicRaycasterCount <= 0;
if (null == _rootGameObject)
return;
// 确保根对象有GraphicRaycaster组件
if (!_rootGameObject.TryGetComponent(out GraphicRaycaster graphicRaycaster))
graphicRaycaster = _rootGameObject.AddComponent();
if (null != graphicRaycaster)
graphicRaycaster.enabled = isEnabled;
// 更新所有子对象的GraphicRaycaster
GraphicRaycaster[] graphicRaycasters = _rootGameObject.GetComponentsInChildren();
foreach (GraphicRaycaster gr in graphicRaycasters)
{
if (null == gr)
continue;
gr.enabled = isEnabled;
}
}
///
/// 获取当前禁用计数
///
/// 禁用计数
public int GetDisableCount()
{
return _disableGraphicRaycasterCount;
}
///
/// 重置禁用计数
///
public void ResetDisableCount()
{
_disableGraphicRaycasterCount = 0;
UpdateGraphicRaycasterState();
}
///
/// 强制启用GraphicRaycaster
///
public void ForceEnable()
{
_disableGraphicRaycasterCount = 0;
UpdateGraphicRaycasterState();
}
///
/// 强制禁用GraphicRaycaster
///
public void ForceDisable()
{
_disableGraphicRaycasterCount = 1;
UpdateGraphicRaycasterState();
}
}