Instancing a node and call a function

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

Hello reader!

I’m having a small trouble with a inconsistence (Possibly i don’t understand something). I’m instancing a node and calling a function, for some reason the variables are initialized from inside of node, but from outside sprite_node is nil, if i use get_node instead the aparently initilized variable it works.

extends KinematicBody2D

export var speed = 0
var new_pos

# Nodes
onready var direction_node = get_node("Direction")
onready var sprite_node = get_node("Sprite")

func _fixed_process(delta):
	#if (direction_node != null):
	new_pos = (direction_node.get_global_pos() - get_global_pos()).normalized()
	move(new_pos * speed * delta)

func _ready():
	set_fixed_process(true)

func set_texture(var tex):
	sprite_node.set_texture(tex)
	# This works..
	# get_node("Sprite").set_texture(tex)

func set_direction(var dir):
	get_node("Direction").set_pos(dir)

func _on_VisibilityNotifier_exit_screen():
	queue_free()

I’m calling set_texture() from Player.gd, instancing this way:

var bullet = preload("res://entities/bullets/Bullet.tscn").instance()
var bullet_texture = preload("res://resources/textures/pickups/special.png")
bullet.set_texture(bullet_texture)
get_node("../..").add_child(bullet)

I would appreciate help, thanks.

PD: I know my english is not perfect.

:bust_in_silhouette: Reply From: Mariano Javier Sulig

sprite_node is referenced onready. ready signal is not emitted until the node enters to the tree, this means you have to add it first before calling set texture

var bullet = preload("res://entities/bullets/Bullet.tscn").instance()
var bullet_texture = preload("res://resources/textures/pickups/special.png")
get_node("../..").add_child(bullet)
bullet.set_texture(bullet_texture)

No way! That was the problem, now i know ready is called when the node enters to the tree, the reason is the most important part, thank you!

Luis Medina | 2017-04-23 19:54

:bust_in_silhouette: Reply From: YeOldeDM

I’m not certain if this will solve your problem, but try adding the child before calling the function. I have a feeling it’s not able to find the Sprite child, because the node is not yet part of the scenetree.