0 votes

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

print(str(new_example.get_script() == ExampleScript)) # returns true.

it prints true.
What is going on here?

Cheers!

in Engine by (21 points)

1 Answer

+1 vote
Best answer

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.

by (10,331 points)
selected by

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.

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.