Spawn(load) object(node) from Globals to level scene

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Bishop
:warning: Old Version Published before Godot 3 was released.

Hi, I trying spawn…load player node by main script(autoload) with Globals
…location for the player works for me but player do’nt load to the level.
Thanks for help

main script (autoload) :

extends Node

var player_location = Vector3(0, -14, -82)
var player_spawn = load("res://scenes/player.scn")


func _ready():
	set_process(true)
	set_process_input(true)
	player_spawn = player_spawn.instance()
	Globals.set("player_location", player_location)
	Globals.set("player_spawn", player_spawn)

and level(Node) script to load-spawn player :

extends Node

var player_spawn



func _ready():
	set_process(true)
	Globals.get("player_spawn")
	print(Globals.player_spawn)
	get_tree().get_root().add_child(player_spawn)

this is from output :

**Debug Process Started**
[RigidBody:701]
**Debug Process Stopped**
:bust_in_silhouette: Reply From: Zylann
Globals.get("player_spawn")

This line doesn’t do anything, you didn’t store player_spawn anywhere, so in your level node, player_spawn will be null and spawn nothing.

I suggest you do this instead:

extends Node

var player_spawn

func _ready():
    set_process(true)
    player_spawn = Globals.get("player_spawn")
    get_tree().get_root().add_child(player_spawn)

Or, simply:

extends Node

func _ready():
    set_process(true)
    get_tree().get_root().add_child(Globals.get("player_spawn"))

Thanks very much,
first try didn’t work with both code sample.
I get error :

Parent node is busy setting up children, add_node() failed. Consider
using call_deferred (“add_child”,child) instead.
so I add call_deferred and this works…great but I get error

 Parameter 'p_child' is null.... in this line : `get_tree().get_root().add_child(player_spawn)`

This works :

extends Node

var player_spawn

func _ready():
	set_process(true)
	player_spawn = Globals.get("player_spawn")
	player_spawn = call_deferred("add_child",player_spawn)
	get_tree().get_root().add_child(player_spawn)

Bishop | 2017-06-19 18:02

Ah, true… not simple having an instance in an auto-load script tbh^^
Then you can also remove get_tree().get_root().add_child(player_spawn) now, and also storing a second time player_spawn is not required:

extends Node

func _ready():
    set_process(true)
    call_deferred("add_child",Globals.get("player_spawn"))

Zylann | 2017-06-19 20:33

Yes, that’s it…totally works!
Thanks very much,Zylann

Bishop | 2017-06-19 21:33