Error in implementing my very first script example in documentation

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

In the documentation there is a script exercise. It’s simple. A button and a label. The documentation shows the following code.

extends Panel

func _ready():
    get_node("Button").connect("pressed", self, "_on_Button_pressed")

func _on_Button_pressed():
    get_node("Label").text = "HELLO!"

I try and execute this code and get the following error:

Script inherits from native type 'Panel', so it can't be instanced in
object of type: 'Node2D'

If I change the code to this:

    extends Node2D
    
    func _ready():
        get_node("Button").connect("pressed", self, "_on_Button_pressed")
    
    func _on_Button_pressed():
        get_node("Label").text = "HELLO!"

everything works fine. But why? What is wrong with the way I’ve implemented the code in the documentation?

Thanks for the help.

:bust_in_silhouette: Reply From: jgodfrey

The script is probably fine. I’d guess you attached it to a different node than the tutorial expected. By the looks of the script, it’s intended to be attached to a Panel node, but you attached it to a Node2D instead.

The script extends the node type it’s attached to. So, that node, and the extends ... line in the script need to be consistent…

First of all, wow. Thanks for the quick response. I’m new to Godot, but have been involved with other programming forums. Not all of them respond nearly this quickly.

I see what I did now. I took the Default Root Node option and renamed it. Now I see that was the wrong thing to do.

Thanks so much for the help.

kevinm56 | 2020-05-14 19:57

Glad you got things working. And, there’s certainly nothing wrong with renaming a node in the tree, but in this case, it actually should have been a different node “type” to begin with. A few tips.

You can switch the “type” of node in the scene tree via the Change Type item in the scene tree’s context menu.

If you’ve renamed a node, you can tell what it’s underlying “type” is either by 1) it’s icon in the scene tree, or 2) by selecting it and looking near the top of the inspector panel.

Welcome to Godot!

jgodfrey | 2020-05-14 20:08