cannot access a instanced child node

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By witch_milk
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…

:bust_in_silhouette: Reply From: jgodfrey

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()  

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

witch_milk | 2020-12-03 22:11