Why does get_parent() return a Null value in a test() function, but an actual value in _ready() ?

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

The node with the attached script is in the main scene and the function is called properly, but when I try and get_parent/tree/root it returns a null value outside of the _ready() and _process(delta) functions.

:bust_in_silhouette: Reply From: USBashka

The script starts executing before all nodes wëre loaded. So you need to call them in _ready() function or onready variables (actually, the common way to do this)

See the docs.

What should I be calling in _ready()/onready?
It seems like the node exists in the parent scene when I print(position) in _ready(), but doesn’t exist when I do the same in a function only a few lines down.

ianstrause | 2022-07-18 04:12

The convention is getting all nodes you need in the variables section of script. That’s how onready variables looks like:

onready var node = get_node("PATH")

And after that you’re using node.

Also, the problem can be in something else, but I’ve no idea what it could be since you haven’t provided code

USBashka | 2022-07-18 04:32

This is the script I’m calling the function from in the main scene.
I keep getting an error with the last line when I try and add_child.

extends KinematicBody2D

var bullet = preload("res://Bullet.tscn")
var bullet_speed = 1500

func _ready():
    $Sprite.rotation_degrees += 180

func _process(delta):
    var Player = get_parent().get_node("Player")

    position = get_global_mouse_position()


func fire():

    var bullet_instance = bullet.instance()
    bullet_instance.position = get_global_position()
    bullet_instance.rotation_degrees = rotation_degrees

ianstrause | 2022-07-18 05:19