Generic scripts on inherited scenes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rainswell

I have three NinePatchRects that I’m using as UI Icons. I’d eventually like each of them to play the same animation whenever the corresponding button on the keyboard is pressed.

Each of them inherits from a base scene. This base scene also has a script with the following in the _ready() function:

print(str(name) + " ready.")

So each of the three scenes should inherit from the same scene and have the same script attached. A number of things are going wrong that I can’t understand:

  • If I leave this code in the _ready() function, it doesn’t get called. I have to put it in _init() instead.
  • This line outputs " ready.", with no object name. It prints three times as expected, once for each of the three inheriting objects.

So first, what part of the architecture am I misunderstanding? It seems like the function is getting called from a generic, nameless version of the inheriting scene, despite each having names like WaterIcon and HandIcon.

Second, would there be a better way to accomplish a scene inheriting a script from its base scene? I’m trying to avoid having a unique script for each scene. Is this possible?

Third, why is _ready() not being called at all?

Thank you, any insight would help.

:bust_in_silhouette: Reply From: Zylann

Your print gets an empty name because _init is in the constructor of the node, the name has not been set yet.

It should definitely be possible to inherit a scene having a script at its root.

_ready should have been called, I’m not sure why it wouldn’t in your case. Did you make a typo in the name? Is the node added to the tree?

Oh! I didn’t think of that, it makes sense that the name wouldn’t be set yet within the constructor. Thank you!

This is the code I have, currently the only code in the script. I’ve just changed _init() to _ready(), and now nothing is getting printed at all:

func _ready():
    print(str(name) + " ready.")
    var node = get_node("../../Interface")
    if node:

Here’s a screengrab of the relevant part of the full scene hierarchy:

CanvasLayer - Album on Imgur

When the game starts, the CanvasLayer is under the “World” node that I’m using as the root node of my scene, so I believe it has been added to the tree. Any idea what I’m doing wrong?

rainswell | 2019-02-28 15:15

I don’t see a script icon on your three NinePatchRects, are you sure there is one? Is it on a child node?

Zylann | 2019-02-28 19:36

That was it! I had forgotten to reset the script to the inherited value, it was null on every instance. Now I’m only wondering how init() was getting called from null scripts.

But anyway, thank you very much. You’ve solved my problem. I appreciate the help.

rainswell | 2019-02-28 23:41