REALLY struggling with classes

Godot Version

4.2.1 stable

Question

so first of all i’m a complete beginner, i don’t know much in code except the very basis of gdscript and i’m currently trying to make a class for my game that would allow me to manage spells better, however, even after watching many tutorials i do not really get how you :

create a class and assign it values that everything in this class should have

assign that class to another node (in my case i’m trying to assign it to an area2D node that is a fireball, i’ve managed to make that fireball work just fine before but i’d like to assign it to the spell class so i can change it easily when i’ll add more spell)

for instance i got my fireball code that works just fine here, i can cast it and it’ll go in a direction and delete itself when it touches a wall, i’d like to add a class so i can add it basic values like damage, cooldown etc…

what i’m pretty much asking is an exemple of how you’d declare and use a class of this type because that’s what i’ve been struggling to find

You probably want to create a “parent”-class. For that you can create a new script and write the following on the top:

class_name Spell extends Area2D

# @export is not necessary here
@export var damage: int
@export var cooldown: float
...

Then you can either extend this script with another script or add it directly to a node:

# Other script
extends Spell

func _ready():
    damage = 100

This script now will inherit everything from the spell-script and is also of type spell

1 Like

alright so my fireball script does understand that it’s child of the spell class but now it tells me that speed already exists in parent class spell, i get what the error means but how do i fix this since i’d like the speed to be different for every spells

You can make multiple unique copies of a class by instantiating it.

If you remove speed from the father and put it inside the child, each time you instantiate “spell”, speed will be unique for each spell you spawned.

1 Like

so if i get it right, classes only serve to apply values that are are true for all childs
for instance wether a child of the spell class will colide against walls or not ?

I don’t want to say something wrong, but theoretically, if you put a code inside the extends Spell script, that code should work only for nodes that are in the class spell.
I don’t use classes very often, so don’t trust 100% what I say.

1 Like

If you want to change this parameter in child classes you can use the @export keyword to change this value in the inspector (Thats why i used them in my example).

You could also use custom resources for that.

A potential problem of the current approach is, that every Spell now extends a Area2D

1 Like

oh okay i get it now, thank you a lot, i’ve been stuck on that for pretty long honestly

have a great day !

1 Like