我尝试编写一个 API,允许以 Unity 的方式创建行为。这只是学习这种语言的一个小实验,我对编程总体来说也是新手。
我制作的测试类应该无限期地将您在构造函数中指定的内容写入控制台,但没有输出。循环似乎被阻塞了。 这是我写的:
1 - 程序.cs
using System.IO;
namespace Program {
public abstract class Script {
public abstract void Start();
public abstract void Update();
}
class Program {
static bool IsKeyDown(ConsoleKey key) {
if (Console.ReadKey(true).Key == key) return true;
else return false;
}
public static void Main(string[] args) {
Script[] scriptList = {
new Write("Hello World"),
};
foreach (Script s in scriptList) {
s.Start();
}
while (!IsKeyDown(ConsoleKey.Escape)) {
foreach (Script s in scriptList) {
s.Update();
}
}
}
}
}
2 - Write.cs
using System;
namespace Program {
public class Write : Script {
string str;
public Write(string _str) {
str = _str;
}
public override void Start(){}
public override void Update(){
Console.WriteLine(str);
}
}
}
最佳答案
您的代码块位于Console.ReadKey上。如果输入缓冲区中没有可用的按键,则 ReadKey 将停止并等待用户按下按键。
您可以在他们所说的文档中阅读此信息
One of the most common uses of the ReadKey() method is to halt program execution until the user presses a key and the app either terminates or displays an additional window of information.
您只需添加
static bool IsKeyDown(ConsoleKey key)
{
if (!Console.KeyAvailable) return false;
if (Console.ReadKey(true).Key == key) return true;
else return false;
}
关于c# - 尝试编写像 Unity 这样的最小行为系统时,循环似乎会阻塞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590332/