Unity中使用Inky创建分支对话时出现选择项越界错误
Unity中Inky分支对话越界错误的解决方法
问题核心错误与修复方案
1. Inky脚本命名与语法错误
你的Inky脚本存在两处关键错误:
No选项跳转的knot名称写错:调用chosen("No")但定义的knot是==chosen1(No)==,名称不匹配导致无法找到对应分支->DONE无对应knot,Inky标准结束指令为-> END
修正后的Inky脚本:
-> main == main == Hello there! My family and I are getting ready to set some traps in the nearby stream. Would you like to hear the story? +[Yes] -> chosen("Yes") +[No] -> chosen("No") == chosen(Yes) == Great news I'll tell you the story! -> END == chosen(No) == Okay come back when you want to hear it. -> END
2. DialogueManager代码逻辑缺失与越界防御
(1)MakeChoice方法补全选择后流程
原方法仅执行选择索引,未触发后续对话流程,且缺少索引合法性检查:
public void MakeChoice(int choiceIndex) { if (choiceIndex >= 0 && choiceIndex < currentStory.currentChoices.Count) { currentStory.ChooseChoiceIndex(choiceIndex); ContinueStory(); // 选择后立即执行后续对话 } else { Debug.LogError("选择索引超出范围:" + choiceIndex); } }
(2)SelectFirstChoice方法增加空选项判断
当对话无选项时,原代码访问choices[0]会直接触发越界错误:
private IEnumerator SelectFirstChoice() { EventSystem.current.SetSelectedGameObject(null); yield return new WaitForEndOfFrame(); // 仅当存在选项且UI支持时设置选中第一个 if (currentStory.currentChoices.Count > 0 && choices.Length > 0) { EventSystem.current.SetSelectedGameObject(choices[0].gameObject); } }
(3)DisplayChoices增强索引防御
遍历选项时增加UI边界检查,避免超出数组范围:
private void DisplayChoices() { List<Choice> currentChoices = currentStory.currentChoices; if (currentChoices.Count > choices.Length) { Debug.LogError("选项数量超出UI支持上限:当前需要" + currentChoices.Count + "个,UI仅支持" + choices.Length + "个"); } int index = 0; foreach(Choice choice in currentChoices) { if (index < choices.Length) { choices[index].SetActive(true); choicesText[index].text = choice.text; index++; } } for (int i = index; i < choices.Length; i++) { choices[i].SetActive(false); } StartCoroutine(SelectFirstChoice()); }
3. UI选项事件绑定验证
确保每个选项按钮的OnClick事件正确绑定:
- 第一个按钮绑定
DialogueManager.MakeChoice(0) - 第二个按钮绑定
DialogueManager.MakeChoice(1)
检查拖放的对象是否为场景中的DialogueManager实例,参数是否与选项顺序对应。
验证步骤
- 将修正后的Inky脚本重新导出JSON文件,替换Unity中原文件
- 更新
DialogueManager脚本代码 - 确认所有选项按钮的事件绑定无误
- 运行游戏测试对话分支,确认无越界错误且分支逻辑正常触发
内容的提问来源于stack exchange,提问作者MarcusLee
相关产品推荐
相关产品推荐

