Skip to main content
 首页 » 编程设计

c#之检测到无法访问的代码问题(但我需要在某处产生返回)

2024年02月05日10Renyi-Fan

问题如下。我正在制作一个打字游戏的变体,我的问题是我需要遍历我的字符数组并检查用户是否按下了正确的键(引入等待用户输入的要求)。当按下右键时,我需要 while 循环停止并返回到 for 循环并重新开始。但是当我 yield return 时,它退出两个循环并且我得到 Unreachable Code Detected。

我知道这意味着 for 循环无法完成它的其余迭代。那么我应该在哪里 yield/return?

IEnumerator TestMyCoroutine() { 
 
    for (int i = 0; i < gCharArray.Length; i++) { 
        string charHolder = gCharArray[i].ToString(); 
 
        while (true) { 
 
            if (Input.anyKeyDown) { 
 
                if (Input.GetKeyDown(charHolder)) { 
 
                } else { 
 
                    print("Wrong Letter"); 
 
                } 
                print(charHolder); 
 
            } 
 
            yield return null; 
        } 
    } 
    print("Word Typing Ended"); 
} 

请您参考如下方法:

When the right key is pressed, I need the while loop to stop and go back to the for loop and start over.

所以... 继续; ?

But when I yield return, it exits both loops and I get Unreachable Code Detected.

不,yield return 不退出任何循环。执行将恢复到原来的位置。

您看到“检测到无法访问的代码”的原因是 while(true) 从不退出,因此它知道 i++ 永远不会达到。如果您在 while (true): 中添加一个 break;,它将正常工作。您还可以添加一个 yield break; 以退出整个枚举器,但这将仍然意味着永远不会达到 i++,并将标记无法访问。