IdleBackToTopManager.cs 2.79 KB
using UnityEngine;
using UnityEngine.UI;

public class IdleBackToTopManager : MonoBehaviour
{
    private float idleTimeThreshold = 300f; // 5分钟
    private float idleTimer = 0f;

    private Vector3 lastMousePosition;
    private Vector3 lastPlayerPosition;

    public GameObject scrollViewContent; // 如果是 ScrollRect,滚动区域
    public ScrollRect scrollRect; // 可选,用于滑动到顶部
    
    private float timer = 0f;

    void Start()
    {
        lastMousePosition = Input.mousePosition;
        // 假设有角色的话可以缓存位置
        lastPlayerPosition = Vector3.zero;
        scrollRect = scrollViewContent.GetComponent<ScrollRect>();

    }

    void FixedUpdate()
    {
        timer += Time.deltaTime;
        if (timer < 1f)
        {
            return;
        }
        
        //如果有滚动,直接返回
        if (scrollRect.velocity.sqrMagnitude > 0.01f)
        {
            return;
        }
        
        // 检测是否有输入
        if (IsUserActive())
        {
            idleTimer = 0f; // 重置计时器
        }
        else
        {
            idleTimer += Time.deltaTime;
        
            if (idleTimer >= idleTimeThreshold)
            {
                GoBackToTop();
                idleTimer = 0f; // 重置,避免重复触发
            }
        }
    }

    bool IsUserActive()
    {
        // 鼠标/触屏移动
        if (Input.mousePosition != lastMousePosition)
        {
            lastMousePosition = Input.mousePosition;
            return true;
        }

        // 任意键按下
        if (Input.anyKeyDown)
        {
            return true;
        }

        // 鼠标点击/拖拽
        if (Input.GetMouseButton(0) || Input.GetMouseButtonDown(0))
        {
            return true;
        }

        // 可以根据项目添加角色或摄像机位置变化的判断
        return false;
    }

    void GoBackToTop()
    {
        Debug.Log("用户5分钟未操作,自动回到顶部");

        if (scrollRect != null)
        {
            scrollRect.verticalNormalizedPosition = 1f; // 回到顶部
        }
        else if (scrollViewContent != null)
        {
            scrollViewContent.transform.localPosition = Vector3.zero; // 也能实现简单重置
        }
        //回到初始化界面
        Transform self = scrollViewContent.transform;
        Transform parent = self.parent;
        int index = self.GetSiblingIndex();
        
        for (int i = 1; i <= 2; i++)
        {
            int nextIndex = index + i;
            if (nextIndex < parent.childCount)
            {
                parent.GetChild(nextIndex).gameObject.SetActive(false);
            }
        }

        

        // 或者调用你自定义的返回主界面函数:
        // UIManager.Instance.GoToHomePage();
    }
}