我希望你用C#写一个在unity中使用的自定义计时器不能继承MonoBehaviour
好的,以下是一个基于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/0ld 著作权归作者所有。请勿转载和采集!