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

Godot Version



I’m a beginner Godot user trying to make Pong.
I have a script that tries to call a function in my script (in the same scene). However, when I try to access the game manager in, 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:

extends Control

@onready var game_manager = %GameManager

func _on_easy_pressed():

func _on_medium_pressed():

func _on_hard_pressed():

# other code
var AI_speed = 2.0

func set_difficulty(difficulty):
	match difficulty:
			AI_speed = 2.5
			AI_speed = 2.0
			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:

in your ChangeDifficulty script:

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

1 Like