Unity 自定义计时器(不继承 MonoBehaviour) - C# 代码示例
以下是一个基于 C# 的自定义计时器,可以在 Unity 中使用,但不继承于 MonoBehaviour。
using System.Collections.Generic;
using UnityEngine;
public class CustomTimer
{
private float currentTime;
private float duration;
private bool isLooping;
private bool isPaused;
private bool isStarted;
private List<System.Action> callbacks;
public CustomTimer(float duration, bool isLooping = false)
{
this.duration = duration;
this.isLooping = isLooping;
this.callbacks = new List<System.Action>();
}
public void Start()
{
this.isStarted = true;
this.isPaused = false;
this.currentTime = 0f;
}
public void Stop()
{
this.isStarted = false;
this.isPaused = false;
this.currentTime = 0f;
}
public void Pause()
{
this.isPaused = true;
}
public void Resume()
{
this.isPaused = false;
}
public void AddCallback(System.Action callback)
{
this.callbacks.Add(callback);
}
public void RemoveCallback(System.Action callback)
{
this.callbacks.Remove(callback);
}
public void Update()
{
if (!this.isStarted || this.isPaused)
{
return;
}
this.currentTime += Time.deltaTime;
if (this.currentTime >= this.duration)
{
foreach (var callback in this.callbacks)
{
callback();
}
if (this.isLooping)
{
this.currentTime -= this.duration;
}
else
{
this.isStarted = false;
}
}
}
}
使用方式如下:
CustomTimer timer = new CustomTimer(2f, true);
timer.AddCallback(() => {
Debug.Log('Timer callback');
});
timer.Start();
void Update() {
timer.Update();
}
这个计时器可以设置持续时间和是否循环,并可以添加回调函数。在 Update() 函数中调用 Update() 方法即可。
原文地址: https://www.cveoy.top/t/topic/mkRY 著作权归作者所有。请勿转载和采集!