Problem With Communicating In Between Scenes

Godot Version

4.2.2

Question

So im trying to make the foundation for my game and heres the code for the GameManager:

extends Node

@export var main_menu:PackedScene = null
@export var game:PackedScene = null

# Called when the node enters the scene tree for the first time.
func _ready():
	add_child(main_menu.instantiate())

# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
	pass
	
func load_main_menu_scene():
	add_child(main_menu.instantiate())

func load_game_scene():
	add_child(game.instantiate())

and heres the code for the button:

extends Button

@onready var ROOT = $".."
@onready var game_manager = %GameManager

func _on_pressed():
	game_manager.load_game_scene()
	ROOT.free()

but when i press the button it gives this error:
E 0:00:00:0559 startButton.gd:4 @ _ready(): Node not found: “%GameManager” (relative to “/root/GameHolder/GameManager/Main_Menu/Button”).
<C++ Error> Method/function failed. Returning: nullptr
<C++ Source> scene/main/node.cpp:1651 @ get_node()
startButton.gd:4 @ _ready()
main.gd:8 @ _ready()

how can i fix this

anyone?

You have probably forgotten to make GameManager a scene-unique node.

it’s supposed to be a globally available node.

I’m confused, why are you doing this?

Thats probably where the issue is.

its to remove the current scene( main menu ) and use the GameManager to load the new scene

the percent sign shorthand %GameManager has to be within the same scene as the button, thus ROOT.free() would also remove GameManager and it’s spawned children. Maybe you want GameManager to be an Autoload?

1 Like

You also want to defer anything you are freeing as well, as otherwise it might try and free whilst its still in use om the same frame.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.