88 lines
2.4 KiB
C#
88 lines
2.4 KiB
C#
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<Action> queue = new();
|
|
List<Action<float>> Updates = new();
|
|
List<Action<float>> FixedUpdates = new();
|
|
public void Add(Action action)
|
|
{
|
|
queue.Enqueue(action);
|
|
}
|
|
public void AddUpdate(Action<float> action)
|
|
{
|
|
Updates.Add(action);
|
|
}
|
|
public void AddFixedUpdate(Action<float> action)
|
|
{
|
|
FixedUpdates.Add(action);
|
|
}
|
|
public void RemoveUpdate(Action<float> action)
|
|
{
|
|
Updates.Remove(action);
|
|
}
|
|
public void RemoveFixedUpdate(Action<float> 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<BehaviourHelper>();
|
|
Singleton = behaviourHelper;
|
|
DI.Register<IMainTicker>(behaviourHelper);
|
|
Debug.Log($"{nameof(IMainTicker)}已创建");
|
|
go.name = nameof(BehaviourHelper);
|
|
go.hideFlags = HideFlags.NotEditable;
|
|
}
|
|
}
|
|
} |