C# 协同程序只在第一次起作用
我假设协同程序有一些基本的东西我不理解,因为我无法理解为什么会发生这种情况 我有一个协同程序,第一次完全按照预期工作,但第二次尝试使用时完全失败C# 协同程序只在第一次起作用,c#,for-loop,unity3d,coroutine,C#,For Loop,Unity3d,Coroutine,我假设协同程序有一些基本的东西我不理解,因为我无法理解为什么会发生这种情况 我有一个协同程序,第一次完全按照预期工作,但第二次尝试使用时完全失败 public IEnumerator CharacterDialogue() { inDialogue = true; playerController.enabled = false; mouselook.enabled = false; Cursor.lockState = CursorLockMode.None;
public IEnumerator CharacterDialogue()
{
inDialogue = true;
playerController.enabled = false;
mouselook.enabled = false;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
dialogueMenu.SetActive(true);
yield return new WaitForEndOfFrame();
for (int i = 0; i < dialogueStrings.Length; i++)
{
while (!Input.GetKeyDown("e"))
{
yield return null;
}
yield return new WaitForEndOfFrame();
dialogueText.text = dialogueStrings[i];
}
yield return new WaitForEndOfFrame();
while (!Input.GetKeyDown("e"))
{
yield return null;
}
yield return new WaitForEndOfFrame();
QuestManager.Instance.SpawnDouxland();
inDialogue = false;
playerController.enabled = true;
mouselook.enabled = true;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
dialogueMenu.SetActive(false);
}
多亏了一些评论,我才明白问题所在
if (Input.GetKeyDown("e"))
{
Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
StartCoroutine(canvasAnimManager.CharacterDialogue());
}
我认为GetKeyDown的想法是它只被触发一次。。。一定有什么我不明白的。不管怎么说,问题是这被调用了多次,它使协同程序在我完成对话后也能通过循环
我只是添加了一点布尔检查来解决这个问题:
if (Input.GetKeyDown("e") && !canvasAnimManager.inDialogue)
{
Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
StartCoroutine(canvasAnimManager.FoukiDialogue());
}
干杯,谢谢你的帮助 协同程序不会无休止地循环。代码本身看起来不错,可能与第二次调用它的方式或位置有关。我不得不说,将输入检测放在非更新函数中可能会变得不可靠。相反,我会将输入放在更新中,然后有一个bool,当按下键时会发生变化。然后在IEnumerator内部,而不是在设置布尔后执行while(!Input)do while(!keyNotHeldDown)。@teebkne实际上我认为在协同程序中检查输入没有问题。在我看来,这比必须将值存储在类字段中并从那里进行轮询检查要干净得多。。。但是是的,请告诉我们你到底怎么称呼这个routine@derHugo感谢您的回答,并指出问题可能不在协同程序本身内部!我用我调用协同程序的代码片段更新了这个问题。
if (Input.GetKeyDown("e") && !canvasAnimManager.inDialogue)
{
Debug.Log("I have interacted with: " + hit.collider.gameObject.name + ".");
StartCoroutine(canvasAnimManager.FoukiDialogue());
}