GDScript中访问数组元素属性时触发Invalid get index 'prompts'错误的问题求助
GDScript中访问数组元素属性时触发Invalid get index 'prompts'错误的问题求助
嘿,我看到你在做填空故事类游戏时遇到了这个索引错误,咱们一步步来把它搞定~
错误根源分析
你触发的Invalid get index 'prompts' (in base 'Array')错误,核心问题是找错了访问对象:
- 你定义的
template是一个数组,里面装着多个包含prompts和story的字典 - 但你在
is_story_done()里直接用template.prompts去访问,数组本身根本没有prompts这个属性,自然会报错! - 你应该用之前随机选中的
current_story变量(它才是数组里的单个字典元素)来访问prompts
修正步骤
- 修复
is_story_done()函数
把原来的代码改成:
func is_story_done(): return player_words.size() == current_story.prompts.size()
- 检查并修复其他类似错误
你的代码里还有两处犯了同样的错误,也要一起修正:
tell_story()函数:func tell_story(): Displaytext.text = current_story.story % player_wordsprompt_player()函数:func prompt_player(): Displaytext.text += "May I Have " + current_story.prompts[player_words.size()] + ", please?"
- 修正拼写错误
我注意到template数组里第三个字典的键写成了"rompts"(少了一个字母p),这个会导致选中该故事时触发新的索引错误,把它改成"prompts"就好:
{ "prompts": ["a name", "a noun", "adverb","adject"], "story":"Habia una vez tres mosqueteros %s, %s, %s y %s" },
额外小建议
可以给prompt_player()里的提示语加个空格和标点,比如改成"May I Have " + current_story.prompts[player_words.size()] + ", please?",这样显示出来的文本会更通顺~
备注:内容来源于stack exchange,提问作者Alejandro Obando
相关产品推荐
相关产品推荐

