I have a simple variable in an autoload called " var Current_Scene" , it has no value assigned to it ( which means its automatically null.
In my game when you click a button, "Current_Scene"s value is SUPPOSED to change to a string called "Main Street". When I check if the value changed in debug it says "Current_Scenes" value is still null. Even when I experimented by presetting "Current_Scenes" value to the string "cat" , After I tried to change it to "Main Street" , debug said it was STILL cat. Idk what I'm missing?
below is my code that checks if my value was properly reassigned: (inside of Scene 2)
func _ready():
if SceneChange.Current_Scene != "Main Street":
print(SceneChange.Current_Scene)
below is my code inside of my autoload that sets up the variable: (inside of an Autoload)
var Current_Scene
below is my code for the button that I want to change my variables value: (inside of a different, Scene 1)
func _on_Button_pressed():
#starts world clock when start button is clicked
WorldClock._WorldTimerStart()
SceneChange.RemoveScene()
SceneChange.enter_main_street()
SceneChange.Current_Scene = "Main Street"
Thank you for any help!
I don't have your scene loading code (RemoveScene
+enter_main_scene
implementation), so I just used get_tree().change_scene(...
. I was not able to reproduce the problem this way so maybe it is in your scene loading/changing code. Please provide your implementation of these methods to elaborate further or try to change it to get_tree().change_scene()
and see if the problem is fixed.
My assumption is that the difference between our cases is that your implementation calls _ready()
callback on second scene BEFORE SceneChange.Current_Scene = "Main Street"
line is executed. If I use get_parent().add_child(secondScene.instance())
instead of get_tree().change_scene()
, that would be the case for me. To fix that swap the lines of code that do the string assignment and adding packed second scene as a child node of a current one.
My implementation:
# Autoload named 'Global'
extends Node
var global_string = "cat"
# Script attached to the root node of "MainStreet.tscn"
extends Node2D
func _ready():
if Global.global_string != "Main Street":
print(Global.global_string)
# Script attached to the button on the first scene:
extends Button
func _on_Button_pressed():
get_tree().change_scene("res://MainStreet.tscn")
Global.global_string = "Main Street"
Fix in case second scene is added with add_child
:
var secondScene = load("res://MainStreet.tscn")
func _on_Button_pressed():
Global.global_string = "Main Street" # should go first
get_parent().add_child(secondScene.instance()) # calls _ready() on second scene
As this Godot tutorial proposes, you could also postpone you scene change with call_deffered("your_method_that_changes_scene")
.
My Godot version is 3.2.3
.