Topic was automatically imported from the old Question2Answer platform.
Asked By
JamesButler
Hello!
I am having trouble accessing the script of a newly instanced scene.
I have a scene called ExampleScene. The root node of that Scene has a script called ExampleScript.
extends Node
class_name ExampleScript
var _name
func init(name : string):
_name = name
In my main scene I want to instance the ExampleScene and call the ExampleScript:
var example = preload("res://ExampleScene.tscn")
func _ready():
var new_example = example.instance()
add_child(new_example)
var script : ExampleScript = new_example.get_script()
script.init("HAHAH") # breaks: Invalid Call. Nonexistent function init in base 'Nil'.
script is Null for some reason but when I test this
No clue about the get_script()-part, but why don’t you simply do it like this?
var example = preload("res://ExampleScene.tscn")
func _ready():
var new_example = example.instance()
add_child(new_example)
new_example.init("HAHAH")
EDIT: According to the documentation get_script()returns a Reference, so the correct static typing would be:
var script : Reference = new_example.get_script()
Doing it your way results in an error for me.
Using this reference to the script you could call it’s static functions, but calling any non-static function won’t work as that would (potentially) require not only knowing about the script but also the specific instance the script is bound to.
Oh… that is indeed what I should do. Thanks.
I came to Godot from Unity. There the script and the node/game object are more strictly separated.