我比较StartCoroutine和Invoke在一个方法中,应该在一个特定的时间执行。根据我的理解,这两个函数应该花费相同的时间(1秒)。使用invoke调用第一个方法大约在1秒内完成,而使用协程则需要将近2秒!这怎么可能呢?
private void iincrease_arrow_invoked(){
if (arrow.transform.localScale.x <= 1f) {
arrow.transform.localScale = new Vector3 (arrow.transform.localScale.x + 0.01f, arrow.transform.localScale.y, arrow.transform.localScale.z);
Invoke ("iincrease_arrow_invoked", 0.01f);
}
}
IEnumerator increase_arrow_coroutine(){
yield return new WaitForSeconds (0.01f);
if (arrow.transform.localScale.x <= 1f) {
arrow.transform.localScale = new Vector3 (arrow.transform.localScale.x + 0.01f, arrow.transform.localScale.y, arrow.transform.localScale.z);
StartCoroutine (increase_arrow_coroutine ());
}
}
IEnumerator
可能运行不止一次,而被调用的函数只运行一次。在您的代码中,您可以通过在IEnumerator
中调用StartCoroutine
来允许IEnumerator
多次运行。
比较InvokeRepeating
和你现有的IEnumerator
将是一个更清晰的比较。
从技术上讲,这是完全不同的,因为你在协程中做任何事情之前等待了整整一秒钟,然后你执行了它,当它再次执行时,你又等待了整整一秒钟。Invoke调用被立即执行,因为您没有像协程那样在它上面添加延迟,然后您要求它等待1秒并重复。如果您希望协程的行为相同,那么将其编码为相同,并将延迟放在最后。
图表会有帮助:StartCoroutine ->>> wait 1 second ->>> do work ->>> wait 1 second当重复时
你想要的是:StartCoroutine ->>> do the work ->>> wait 1 second ->>> do the work when repeat
只有看起来用你的方式花了2秒。
在开始比较它们之前更应该是这样的:
WaitForSeconds delay = new WaitForSeconds(0.01f);
IEnumerator increase_arrow_coroutine() {
if(arrow.transform.localScale.x <= 1.0f) {
arrow.transform.localScale = new Vector3(
arrow.transform.localScale.x + 0.01f,
arrow.transform.localScale.y,
arrow.transform.localScale.z);
}
yield return delay;
StartCoroutine(increase_arrow_coroutine());
}
对我来说,除非你在其他地方有其他延误,否则你花那么长时间还是不太有意义。它应该只需要0.01秒,但那是另一个故事。