using System; using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.Events; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Collections.Concurrent; using Cysharp.Threading.Tasks; namespace BITKit { public class BehaviourHelper : MonoBehaviour, IMainTicker { public static Action OnStop; public static bool Actived; static BehaviourHelper Singleton; ConcurrentQueue queue = new(); List> Updates = new(); List> FixedUpdates = new(); public void Add(Action action) { queue.Enqueue(action); } public void AddUpdate(Action action) { Updates.Add(action); } public void AddFixedUpdate(Action action) { FixedUpdates.Add(action); } public void RemoveUpdate(Action action) { Updates.Remove(action); } public void RemoveFixedUpdate(Action action) { FixedUpdates.Remove(action); } void Update() { lock (queue) { while (queue.TryDequeue(out var action)) { try { action.Invoke(); } catch (System.Exception e) { Debug.LogError(e); } } } foreach (var update in Updates.ToArray()) { update.Invoke(Time.deltaTime); } } void FixedUpdate() { foreach (var fixedUpdate in FixedUpdates.ToArray()) { fixedUpdate.Invoke(Time.fixedDeltaTime); } } void OnDestroy() { OnStop?.Invoke(); } [RuntimeInitializeOnLoadMethod] static void Initialize() { GameObject go = new(); GameObject.DontDestroyOnLoad(go); var behaviourHelper = go.AddComponent(); Singleton = behaviourHelper; DI.Register(behaviourHelper); Debug.Log($"{nameof(IMainTicker)}已创建"); go.name = nameof(BehaviourHelper); go.hideFlags = HideFlags.NotEditable; } } }