协程只触发一次
Coroutine only firing once
我正在尝试 运行 一个脚本,该脚本将在 a 点和 b 点之间的触摸时生成 "ramps"。此代码接收坡道元素应在何处的列表,然后实例化并将它们放置在屏幕上。
但是协程只有 运行ning 一次,我不明白为什么。谁能给我一些建议?
非常感谢您
public IEnumerator CreateRamp(List<Vector3> lP, float angle)
{
int i = 1;
while (i <= lP.Count)
{
Debug.Log("Iteration " + i + " of " + lP.Count + " position is " + lP[i]);
GameObject item = Instantiate(Resources.Load("floor")) as GameObject;
item.transform.position = current_Position;
item.transform.eulerAngles = new Vector3(0, 0, UnityEngine.Random.Range(0f, 360f));
item.GetComponent<Ramp>().strtPos = item.transform.position;
item.GetComponent<Ramp>().strtRot = item.transform.eulerAngles;
item.GetComponent<Ramp>().strtScale = new Vector3(0.4f, 0.4f, 1);
item.GetComponent<Ramp>().tgtRot = new Vector3(0, 0, angle);
item.GetComponent<Ramp>().tgtPos = lP[i-1];
i += 1;
yield return new WaitForSeconds(0.2f);
}
}
由于此函数是一个 IEnumerable,其他代码应将其视为 Ramp
个对象的列表。我怀疑(你的代码不够多,无法知道),你调用这个函数的方式不正确。
附带说明一下,随着您的 yield 返回 waitforX,从长远来看,最好在该函数之外(您从中调用它的地方)执行等待,或者至少添加等待period 作为函数的参数。像这样的硬编码值会在以后对您不利,尤其是当您的游戏代码库增长时。我建议将它作为 GameObject 的设置公开,这样就可以从编辑器中对其进行调整。
还有一件事,当你用完这些 Ramp 对象时,你如何销毁它们?最好在创建它们时考虑存储对它们的引用,以便稍后销毁它们。
我怀疑你的条件 i <= lP.Count
只有一次为真。 (我想也许 lP.Count == 1
)。
协程的工作方式是,CreateRamp
函数中的代码是跨帧执行的。
当你 StartCoroutine(CreateRamp(...))
时,它会立即 运行 直到它命中 yield 语句。它将在那里等待 0.2 秒,然后将在 yield 后立即从语句中再次 运行。
在第二次执行时,它再次评估条件i <= lP.Count
,看到它是False
=> 它跳出了循环,因为它到达了函数的末尾,所以co -例程将停止,以后不再执行。
我正在尝试 运行 一个脚本,该脚本将在 a 点和 b 点之间的触摸时生成 "ramps"。此代码接收坡道元素应在何处的列表,然后实例化并将它们放置在屏幕上。
但是协程只有 运行ning 一次,我不明白为什么。谁能给我一些建议?
非常感谢您
public IEnumerator CreateRamp(List<Vector3> lP, float angle)
{
int i = 1;
while (i <= lP.Count)
{
Debug.Log("Iteration " + i + " of " + lP.Count + " position is " + lP[i]);
GameObject item = Instantiate(Resources.Load("floor")) as GameObject;
item.transform.position = current_Position;
item.transform.eulerAngles = new Vector3(0, 0, UnityEngine.Random.Range(0f, 360f));
item.GetComponent<Ramp>().strtPos = item.transform.position;
item.GetComponent<Ramp>().strtRot = item.transform.eulerAngles;
item.GetComponent<Ramp>().strtScale = new Vector3(0.4f, 0.4f, 1);
item.GetComponent<Ramp>().tgtRot = new Vector3(0, 0, angle);
item.GetComponent<Ramp>().tgtPos = lP[i-1];
i += 1;
yield return new WaitForSeconds(0.2f);
}
}
由于此函数是一个 IEnumerable,其他代码应将其视为 Ramp
个对象的列表。我怀疑(你的代码不够多,无法知道),你调用这个函数的方式不正确。
附带说明一下,随着您的 yield 返回 waitforX,从长远来看,最好在该函数之外(您从中调用它的地方)执行等待,或者至少添加等待period 作为函数的参数。像这样的硬编码值会在以后对您不利,尤其是当您的游戏代码库增长时。我建议将它作为 GameObject 的设置公开,这样就可以从编辑器中对其进行调整。
还有一件事,当你用完这些 Ramp 对象时,你如何销毁它们?最好在创建它们时考虑存储对它们的引用,以便稍后销毁它们。
我怀疑你的条件 i <= lP.Count
只有一次为真。 (我想也许 lP.Count == 1
)。
协程的工作方式是,CreateRamp
函数中的代码是跨帧执行的。
当你 StartCoroutine(CreateRamp(...))
时,它会立即 运行 直到它命中 yield 语句。它将在那里等待 0.2 秒,然后将在 yield 后立即从语句中再次 运行。
在第二次执行时,它再次评估条件i <= lP.Count
,看到它是False
=> 它跳出了循环,因为它到达了函数的末尾,所以co -例程将停止,以后不再执行。