How to fix " attempt to call function null instance" When passing a function from a different script to change scene?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Xian

I wanted to change scene when i press a button, using a function from my GameManager Script. My GameManager Script was made to hold all my functions to prevent redundancy. My button is named “Start” and it has a script called “” and inside is.

extends Button

var GM = load("res://Scripts/").new()

func _on_Start_pressed():

Inside my GameManager is the function

func changeScene(Scene:String):
	var ret = get_tree().change_scene(Scene) 
	if ret != 0:
		logError("Scene error#"+ret+". Could not change to Scene:\""+Scene+"\"")

Disregard logError it is just a func that writes error into an error file. The problem here is that if i wrote this code in my it will work just fine but when i use it from it cause the error “attempt to call function ‘change_scene’ in base “null instance” on a null instance”. How do I fix this? I have an inkling idea that maybe because the target node was different between the two scripts.(Forgive me I am still a student programmer)

:bust_in_silhouette: Reply From: Dlean Jeans

You need to add GM to the scene tree, as a singleton or in _ready:

func _ready():

The reason for this is get_tree() only works for node in the scene tree, otherwise it returns null, hence the error.

thanks as always Dlean Jeans it works xD
What you said about

The reason for this is get_tree() only works for node in the scene
tree, otherwise it returns null

Actually gave me a cool idea after I fixed the error using your advice. I found a different way. Where i just pass the “self” as a second argument. And it worked since the “self” or node was already in the scene xD thank you! i learned plenty of new things

func changeScene(Scene:String, callerNode:Node):
	var ret = callerNode.get_tree().change_scene(Scene) 
	if ret != 0:
		logError("Scene error#"+String(ret)+". Could not change to Scene:\""+Scene+"\"")

Xian | 2019-07-20 23:33