0 votes
onready var instanced_child = preload("res://child.tscn")

func instance_child(): 
var child = instanced_child.instance()
self.add_child(child)

func do_something_with_child():
$child.do_something()                 #I want to be able to do this

I know that if you add " onready var child" to the top of the script it will work but I do not want to do that because I am trying to make a seperate instance of this child variable for every player without writing out child1, child2 , child3...

in Engine by (56 points)

1 Answer

0 votes
Best answer

Your child variable is local to the instance_child() function (because it was defined inside that function). Because of that, the child variable is not recognized anywhere outside of that function. To fix it, you need to define the child variable outside of any function. So, this:

onready var instanced_child = preload("res://child.tscn")
var child # <--- defined here

func instance_child(): 
    child = instanced_child.instance() # <--- note, no "var" keyword
    self.add_child(child)

func do_something_with_child():
    $child.do_something()  
by (10,890 points)
edited by

thanks for the reply.
i have just started using get_node(child).variable and its working great so far

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.