using System; using System.Collections.Generic; using Framework.Timer; using Framework.Utils.SingletonTemplate; using UnityEngine; namespace Game.Component { public class GyroscopeMgr : MgrMonoBase { public Gyroscope Gyroscope => Input.gyro; protected override void InitMgr () { this._UpdateList = new List> (); } 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> _UpdateList; private void _InvokeUpdate(List> 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 updater) { this._UpdateList.Add(updater); CheckEnable (); } public void RemoveUpdater(Action updater) { this._UpdateList.Remove(updater); CheckEnable (); } } }