gdscript全局变量值在get_tree()。​​reload_current_scene()之后保持不变

时间:2019-05-14 06:32:49

标签: game-engine game-development godot gdscript

我想要变量

  

first_playthrough

成为false,因此在场景重新加载时,它将不再显示文本“来自Number Guesser的Hello” 。但它仍在显示。

因此,它要么是:它从未变成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

一种解决方案是持久性数据存储。 但是也许对于像这样的简单游戏,不再需要了吗? 我在这里做什么错了?

如果需要,我将发布整个脚本。

1 个答案:

答案 0 :(得分:1)

以我也在其中发布问题的其他网站的答案为基础。

创建了声明为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个。

Singleton文档链接: https://docs.godotengine.org/en/3.1/getting_started/step_by_step/singletons_autoload.html?highlight=autoload