0 votes

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 spritenode is nil, if i use getnode 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.

in Engine by (15 points)

2 Answers

+4 votes
Best answer

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)
by (63 points)
selected by

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!

0 votes

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.

by (1,328 points)
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.