Unity中如何按数组顺序依次检测匹配用户对应按键输入
问题描述
我是开发初学者,不清楚该功能的正确实现方式。
我希望实现如下效果:用户在对话流程中输入对应字母后,自动切换到数组的下一个字符进行匹配校验,按此逻辑依次完成整段对话文本的输入检测。我原本以为编写的代码可以实现该效果,但实际运行不符合预期,原代码如下:
private string[] type; private string dialogue; // Start is called before the first frame update void Start() { dialogue = "ThisIsATest"; type = new string[dialogue.Length]; for (int i = 0; i < dialogue.Length; i++) { type[i] = System.Convert.ToString(dialogue[i]); } } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.type[i])) { Debug.Log("It works!"); } }
原代码存在的问题
- 未声明当前匹配位置的索引变量
i,Update方法中直接调用i会触发编译错误,代码无法正常运行 KeyCode是Unity内置的枚举类型,不支持KeyCode.type[i]这种动态拼接枚举值的写法,语法本身不成立- 缺少索引自增逻辑,即使按键检测正常,也无法自动切换到下一个待匹配的字符
- 未做边界校验,当索引超过对话文本长度时会触发数组越界异常
可直接运行的修复代码
private string dialogue; // 记录当前需要匹配的字符位置,从0开始 private int currentMatchIndex = 0; void Start() { dialogue = "ThisIsATest"; } void Update() { // 所有字符都匹配完成后不再检测输入 if (currentMatchIndex >= dialogue.Length) { return; } // 拿到当前需要匹配的字符,统一转大写匹配KeyCode枚举 char currentChar = char.ToUpper(dialogue[currentMatchIndex]); // 将字符转换为对应的KeyCode枚举值 KeyCode targetKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), currentChar.ToString()); if (Input.GetKeyDown(targetKey)) { Debug.Log($"匹配成功第{currentMatchIndex + 1}个字符:{dialogue[currentMatchIndex]}"); // 匹配成功后索引自增,切换到下一个待匹配字符 currentMatchIndex++; // 全部匹配完成的提示 if (currentMatchIndex == dialogue.Length) { Debug.Log("整段对话文本输入检测完成!"); } } }
说明:如果需要支持小写输入匹配,只需要在转换KeyCode前判断字符大小写,对应处理枚举解析逻辑即可;如果需要支持数字、符号类字符匹配,可自行扩展字符到KeyCode的映射规则。
内容的提问来源于stack exchange,提问作者Abu fadel Abas
相关产品推荐
相关产品推荐

