我想要变量
first_playthrough
变为false
,这样当场景重新加载时,它就不会再显示文本“Hello from Number Guesser”。但它仍然显示它。
因此,要么是:它从未变成 false
,或者它变成 false
,但随后又回到 true
。
代码的简化版本:
extends Node
var first_playthrough = true
func _ready():
# this is here so it will show the message
first_playthrough_checker()
func first_playthrough_checker():
# problem here is that, the message below still shows even though i thought i set it to 'false' already.
if first_playthrough == true:
text_printer("Hello from Number Guesser!\n\n")
func _restart_game():
#I've tried everywhere else. Thought it would work here. i was wrong.
get_tree().reload_current_scene()
first_playthrough = false
一种解决方案是持久数据存储。 但也许对于像这样的简单游戏来说,它不再需要了? 我在这里做错了什么?
如果需要,我会发布整个脚本。
最佳答案
基于我也发布问题的另一个网站的答案。
创建声明了 first_playthrough
的单例 globals 后,我将脚本上变量的所有实例替换为 globals.first_playthrough
。
因此,在代码的缩短版本中,如下所示:
extends Node # removed the declaration here already, since it's already declared in globals.gd func _ready(): # this is here so it will show the message first_playthrough_checker() func first_playthrough_checker(): # message below doesn't show anymore after globals.first_playthrough becomes false. if globals.first_playthrough: text_printer("Hello from Number Guesser!\n\n") func _restart_game(): #I haven't tested it but i suspect the line after reloading the scene will create a memory leak? #So i changed globals.first_playthrough's value before reloading the scene instead. globals.first_playthrough = false get_tree().reload_current_scene()
脚本现在按预期工作。
通过学习使用单例,我了解到:
- 即使在单个脚本中也可以声明类的全局变量 项目并没有使其真正全局化。
- 只有在项目中如此声明的对象才是全局的。
- 我应该记住,我仍在使用框架。
- 使用 gdscript,我有 3 个选项来存储持久信息。其中 2 个是最值得推荐的。
关于game-engine - get_tree().reload_current_scene() 之后 gdscript 全局变量值没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124273/