What is a use case of the class_name keyword

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

Dear community,

I wonder how the class_name keyword is useful. I understand that it registers a script as a class in the editor and that I can choose it when adding a node. The node is created and the script is attached, but that means I can’t have an additional script for that node, to extend it’s functionality.

Then I thought I could use it to make components like KinematicBody2D. Imagine I have an alarm light which has a Sprite and a Light2D as child nodes.

  • AlarmLight : Node2D
    – AlarmLamp : Sprite
    – PulsingLight : Light2D

I created a script alarm_light.gd which changes the light energy of my child node PulsingLight , so that the light is pulsing. The script registers a class AlarmLight. Now I can choose AlarmLight from the add node list, but it just creates a Node2D with the script alarm_light.gd attached to it. The child nodes are missing. I was thinking about creating the child nodes in my alarm_light.gd script, but realized that the component is actually my scene with the above described hierarchy.

The only thing I could imagine, is to write a script pulsing_light.gd and register it as PulseLight which I could then use for any kind of pulsing light. But that could be solved by deriving from a pulsing_light.gd script and let me room for adding functionality in the actual script.

The worst is, that even if I registered a class via class_name I can’t just derive from it by writing

extends ClassName

Instead I have to extend from the full script path.

How do you use the class_name keyword?
How can I create a component like KinematicBody2D which comes with all needed child nodes?

Thanks and best,
Gentle22

:bust_in_silhouette: Reply From: brainbug

for me

extends ClasName

works !!

Also :

if is ClassName:...

and

… as ClassName

and

var c : ClassName = ClassName.new()

or

var c  := ClassName.new()

Ok you are right, no idea why it did not work in the first place. Maybe I just expected a code completion.

Gentle22 | 2019-04-06 15:48