game-engine - get_tree().reload_current_scene() 之后 gdscript 全局变量值没有改变

标签 game-engine game-development godot gdscript

我想要变量

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 个是最值得推荐的。

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

关于game-engine - get_tree().reload_current_scene() 之后 gdscript 全局变量值没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56124273/

相关文章:

c++ - 授予另一个类访问特定方法的权限

java - 墙壁上的 Pong 反射

java - Libgdx 渲染网格问题

godot - 如何在工具模式下绘制Shape2D?

java - 哪个 2D 游戏引擎适用于 native 应用程序内的跨平台模块

使用移动 pkg 的 Golang 跨平台游戏引擎?

sprite - 让 Godot "Script Variables"控件在 2D 编辑器中出现?

glsl - 如何获得 godot 空间着色器的分辨率?

javascript - 方 block 基础游戏的颜色系统

c++ - 为某事获取错误 "...does not have a name type"