IdleBackToTopManager.cs
2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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();
}
}