Reputation: 55730
I'd like to be able to define a component made of multiple nodes that I can reuse. Take for example the image below, where I have a custom Button node that has a Sprite2D as a child and a script that manages its behavior.
In this image, I have done the following steps manually twice:
But this has many limitations:
I tried registering the class as DeleteMe
(this is an example) so I can add it as its own node, but then the child Sprite2D doesn't come with it.
class_name DeleteMe
extends Button
But as you can see, the Sprite2D child node didn't get added with it, neither did the shape, size, and text, that I set manually from the first two nodes.
I suspect this is a complete n00b question and I'm showing my ignorance by even asking it, but how do I define this DeleteMe
component such that it will show up correctly in the Godot editor, and reproduce consistently?
I know I can define things programmatically in the code, perhaps by setting the text and creating the child node via _init()
in GDScript, but I want the text and the child node to be visible when I use it in the editor.
And if I write the following in GDScript:
class_name DeleteMe
extends Button
func _init():
text = "Example"
And then add it to the scene, I don't see "Example" as the button text!
Upvotes: 1
Views: 2998
Reputation: 126
There are two ways to do that in Godot.
The first one is the one you are trying right now. You start by declaring a script with the class_name
keyword but then you need to create each component through code. Additionally, those changes should be made in the _ready
method instead of _init
, since _init
is called way too early.
Something like this:
class_name DeleteMe
extends Button
func _ready():
text = "Example"
# Then you need to add the sprite as a child an set each property separately
var sprite = Sprite2D.new()
sprite.texture = preload('..path to texture')
sprite.position = Vector2(0, 100)
add_child(sprite)
class_name
does not add the scene to the list of user defined classes, only the script. So any changes made to the scene would not be propagated to the new node.
However there is a better way to create reusable components in Godot.
Create a scene with only the button and the sprite. Then change any properties there.
Now you can use this component like this:
var DeleteMe = preload('...path to my component')
var deleteMe = DeleteMe.instantiate() # or .instance() if Godot 3
add_child(deleteMe)
Upvotes: 2