0 votes

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').

Godot version 3.3.3.stable.mono
in Engine by (177 points)

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

2 Answers

+1 vote
Best answer

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.

by (46 points)
edited by
0 votes

Solved:

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

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

by (177 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 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 webmaster@godotengine.org with your username.