Calling a function of a script from another script in the same scene

Godot Version

4.0

Question

I’m a beginner Godot user trying to make Pong.
I have a ChangeDifficulty.gd script that tries to call a function in my GameManager.gd script (in the same scene). However, when I try to access the game manager in ChangeDifficulty.gd, it is null.
I’ve set the game manager as a unique reference so there’s no question about the path.

Please see the code snippets below:

ChangeDifficulty.gd:

extends Control

@onready var game_manager = %GameManager

func _on_easy_pressed():
	game_manager.set_difficulty("easy")
	get_tree().change_scene_to_file("res://scenes/game.tscn")

func _on_medium_pressed():
	game_manager.set_difficulty("medium")
	get_tree().change_scene_to_file("res://scenes/game.tscn")

func _on_hard_pressed():
	game_manager.set_difficulty("hard")
	get_tree().change_scene_to_file("res://scenes/game.tscn")

GameManager.gd:

# other code
var AI_speed = 2.0

func set_difficulty(difficulty):
	match difficulty:
		"easy":
			AI_speed = 2.5
		"medium":
			AI_speed = 2.0
		"hard":
			AI_speed = 1.5

Here’s my scene structure:

The project’s main scene is set to MainMenu, which uses get_tree().change_scene_to_file("res://scenes/game.tscn")
to switch to the game scene (its parent node). Could this be a problem?
Any help would be appreciated. Thanks.

Yes, so do like this:

@onready var game_manager = #Drag and drop the node here 

Unique nodes has some limitations as you can see here, you can’t acess a node outside the scene you’re using the code, i recommend you to use groups instead.

In your GameManager script:

func _ready() -> void:
	add_to_group("game_manager")

in your ChangeDifficulty script:

Replace: game_manager.set_difficulty("dificult") to get_tree().call_group("game_manager", "set_difficulty", "difficult")

1 Like