What is Classes all about?

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

I don’t really understand classes that much and I want to understand them. Can anyone teach me what it is for, examples of how you will use it and why ?

:bust_in_silhouette: Reply From: Andrea

long story short, by declaring a class_name YourCustomClassyou basically create your very own node, with his own methods and properties.

you can obviously use them to instance new nodes, but this is not really the reason they are meant to (i mean, you can instance any saved scene without creating the class): the real streanght is that, after creating a class, a new node can inherit that class, meaning you can build nw methods and properties upon the methods and properties of the original class.

Eg: you create a class inheriting a kinematic body, and call it GenericProjectile. In this class you place all that is shared by every projectile in your game (move_and_slide, collision, queue_free, etc). Then you create a new scene called FireBolt , that inherit the GenericProjectile.
FireBolt will still move and act as a generic projectile, but you can add a the new method explode() after collision is detected.

I dipped into using class_name in 3.2 and I have to say ‘use with caution’. The keyword doesn’t actually represent a class in OO sense and for those used to OO languages they may run into pitfalls thinking of it as a type declaration.

If you use the name as a type like:

class_name AnotherThing

var thing:TheThing

too cavalierly, godot 3.2 is prone to complaining about cyclic dependencies when you put that declaration in another ‘class_name’-ed script file. Also if you “sub-class” TheThing or AnotherThing and add class_name to the inheriting script you can also see complaints.

So for 3.2, use with caution.

It is best to think of it as a labeling for editor hints and scene creation workflow more than a OO ‘class’.


dotty | 2021-03-21 15:51

If it is that way, can I modify the variables and method if I extend the class_name Anothername?

Mrpaolosarino | 2021-03-22 10:47

from the original class yes, from the extended Anothername, i dont think so, you have to find a way to build them like a tree structure, each one on top of the other

Andrea | 2021-03-22 11:23


Yes it works just like any other extension of script or base node, just with more ‘cyclic dependency’ errors from the engine.

IIRC the worst way the errors show themselves might be something like having vars that refer to the base extension “TheThing” in a “TheChildThing” script.

Feel free to make a quick test of this, but I’ve learned to be a judicious in the use of class_name, such as avoiding its use in var and parameter typing. In the latter case, overriding the function can cause issues mention above.

dotty | 2021-03-22 14:28