0 votes

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 "Start.gd" and inside is.

extends Button

var GM = load("res://Scripts/GameManager.gd").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 Start.gd it will work just fine but when i use it from GameManager.gd 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)

in Engine by (271 points)

1 Answer

+1 vote
Best answer

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.

by (4,221 points)
selected by

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+"\"")
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.