Hello, I have an Actor class with two sub-classes, Player and Enemy. I have a signal on my Actor class and I want the signal to be inherited on my sub classes. How can I do this?
Here is the code right now:
func _on_Actor_body_entered(body):
print(body.name)
I want that to be on all my sub classes, (yes, technically I could just add signals to my sub-classes and copy the code, but that is ugly.)
Share signals on subclasses?
- Edited
How are you connecting the signal? Are you connecting it through code, or in the Godot Editor?
If you are connecting the signal in code, then as long as you do not override the function by having a function with the exact same name in your sub-classes, it should use the function defined in the parent class.
If you are connecting the signal through the Godot editor, I'm afraid I do not know. Probably, you just need to connect the signal to a function with a function defined in the base class, without overriding it in the sub-class. That said, I do not really connect signals through the Godot editor and am just guessing on how it might work.
A way you could work around this is break the function you want to call when the signal happens into it's own function, and then call that function when the signal is triggered. For example, in the base class:
extends Node2D
class_name base_class
func on_body_enters_actor(other_body):
print (other_body.name, " hit actor with name ", name)
Then in your sub-classes:
extends base_class
func _ready():
# example: connect the signal:
get_node("Area2D").connect("body_entered", this, "_on_body_entered")
func _on_body_entered(body):
# Call the function defined in the base class!
on_body_enters_actor(other_body)
Edit: Using this method, you would still have to connect every signal with each subclass, but the code would just call a function defined in the base class, allowing the same code to be used across all sub-classes.
@TwistedTwigleg Then is there any reason to use signals through the Godot editor?