有什么方法可以控制Unity中的时间延迟

本文关键字:Unity 时间延迟 控制 什么 方法 | 更新日期: 2023-09-27 18:24:30

我环顾四周,显然我在以下库/解决方案之间做出了选择:

一:

public void Awake() {
    Invoke("InvokeAndPrint", 2);
}
void InvokeAndPrint() {
    print("InvokeAndPrint 2");
}

二:

void Start() {
    StartCoroutine(WaitAndPrint(2.0F));
}
IEnumerator WaitAndPrint(float waitTime) {
    yield return new WaitForSeconds(waitTime);
    print("WaitAndPrint " + Time.time);
}

我想知道是否还有其他更好的方法?

有什么方法可以控制Unity中的时间延迟


这是我在上的评论摘要


我唯一能想到的另一种方法是老派在开始时记下时间;然后在Update()方法中检查经过的时间。你基本上每件事都是自己做的。尽管它比上面的例子详细得多,但它是类型安全的,不需要任何额外的线程或线程作业对象。

最简单的

首先,我们需要定义一些字段:

private DateTime _start;
private bool _done;

在你开始的时候记下时间:

void Start()
{
    _start = DateTime.Now;
}

然后在您的更新中检查已经过了多少时间。如果它大于你的超时时间,比如说2秒,发射你想做的任何事情——在这种情况下是print():

void Update()
{
    if (! _done && (DateTime.Now - _start).TotalSeconds >= 2)
    {
        print("hello world");
        _done = true;
    }
}

就是这样。

可重复使用代码

你可能会发现,在很多地方都需要这样做,所以如果有一种方法可以减少重复代码,那不是很好吗。也许是一节课来结束它?

class DelayedJob
{
    private readonly TimeSpan _delay;
    private readonly Action _action;
    private readonly DateTime _start;
    public DelayedJob(TimeSpan delay, Action action)
    {
        if (action == null)
        {
            throw new ArgumentNullException("action");
        }
        _delay = delay;
        _action = action;
        _start = DateTime.Now;
    }
    /// <summary>
    /// Updates this instance.
    /// </summary>
    /// <returns>true if there is more work to do, false otherwise</returns>
    public bool Update()
    {
        if (DateTime.Now - _start >= _delay)
        {
            _action();
            return false;
        }
        return true;
    }
}

然后你可以做这样的事情:

void Start()
{
    _job = new DelayedJob(TimeSpan.FromSeconds(2), ()=> print("hello"));
}

相应地更新您的Update()之后:

void Update()
{
    if (_job != null && !_job.Update())
    {
        _job = null;
    }
}

多个作业

这只是将它们放在集合中并在运行时进行处理的问题。

private List<DelayedJob> _jobs; 
void Start()
{
    _jobs = new List<DelayedJob>
            {
                new DelayedJob(TimeSpan.FromSeconds(2), () => print("star wars")),
                new DelayedJob(TimeSpan.FromSeconds(3f), () => print("is coming!"))
            };
}

Update():的几点修改

void Update()
{    
    bool again;
    do
    {
        again = false;
        // you probably want to optimise this so that we don't check the same items
        // at the start again after removing an item
        foreach (var delayedJob in _jobs)
        {
            if (!delayedJob.Update())
            {
                _jobs.Remove(delayedJob);
                again = true; // start over
                break;
            }
        }
    }
    while (again);    
}