Files
taptap2024_GJ_chidouren/Assets/Scripts/Game/Component/GyroscopeController/GyroscopeMgr.cs
2024-10-16 00:03:41 +08:00

83 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using Framework.Timer;
using Framework.Utils.SingletonTemplate;
using UnityEngine;
namespace Game.Component
{
public class GyroscopeMgr : MgrMonoBase<GyroscopeMgr>
{
public Gyroscope Gyroscope => Input.gyro;
protected override void InitMgr ()
{
this._UpdateList = new List<Action<Vector3>> ();
}
private void OnEnable ()
{
GameUpdateMgr.Instance.AddUpdater (DoUpdate);
}
private void OnDisable ()
{
this._UpdateList?.Clear ();
GameUpdateMgr.Instance.RemoveUpdater (DoUpdate);
}
private void CheckEnable ()
{
if (this._UpdateList is { Count: > 0 } && !Input.gyro.enabled)
{
Input.gyro.enabled = true;
Input.gyro.updateInterval = 0.1f;
return;
}
if (this._UpdateList!.Count == 0 && Input.gyro.enabled)
{
Input.gyro.enabled = false;
return;
}
}
private List<Action<Vector3>> _UpdateList;
private void _InvokeUpdate(List<Action<Vector3>> list)
{
if (list == null)
{
return;
}
for (int i = list.Count - 1; i >= 0; i--)
{
//在遍历时可能会出现外部操作list导致Count改变
if (i >= list.Count)
continue;
if (list[i] == null)
{
list.RemoveAt(i);
}
else
{
list[i].Invoke(Input.gyro.gravity);
}
}
}
private void DoUpdate() => this._InvokeUpdate(this._UpdateList);
public void AddUpdater(Action<Vector3> updater)
{
this._UpdateList.Add(updater);
CheckEnable ();
}
public void RemoveUpdater(Action<Vector3> updater)
{
this._UpdateList.Remove(updater);
CheckEnable ();
}
}
}