Invalid get index 'knockback' (on base: 'null instance').

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

So I have an Enemy node that has a child node called DamageArea. I’m trying to get a variable from Enemy node to DamageArea node.

Enemy code:

var knockback = 300

DamageArea code:

var knockback = get_parent().knockback

Error that I get: Invalid get index ‘knockback’ (on base: ‘null instance’).

On further inspection it appears that calling get_parent() from the DamageArea node returns null. But DamageArea certainly has a parent.

JorensM | 2021-09-12 18:08

:bust_in_silhouette: Reply From: TonyTony

When you run a scene your script instance is created but hasn’t yet entered the tree, that’s why your DamageArea still has no parent (hence the get_parent() gives you a null instance).
What you need to do is either declare the variable on the ready function (wich runs right after your node and children enter the scene tree):

func _ready():
    var knockback = get_parent().knockback

Or much easier, just declare it as an onready var, it does the same but less bloated:

onready var knockback = get_parent().knockback

Hope it helped.

:bust_in_silhouette: Reply From: JorensM

Solved:

I solved this by putting the get_parent() function inside _ready()

Maybe this is how it’s supposed to work, idk