💾 Archived View for lertsenem.com › 20210401.godot.gmi captured on 2024-05-12 at 15:07:30. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2021-11-30)

-=-=-=-=-=-=-

How to write classes in Godot

For some reason I seem to always forget how to do this, so I'll write it here in hope that it will help me remember it (and maybe it will help someone else too?).

A class in Godot is just a gd script

That's about it.

What you think are the script global variables are actually the class properties. And of course your functions are the class method. You can of course inherit other classes/scripts by using the `extends` keyword on the first line like in the following examples :

extends Node2D
extends "res://my/directory/my_sript.gd"

You use load() to "import" a class/script

For instanciation, like in every language, you first need to import the script using `load()`:

var MyClass = load("my_class.gd")

This should give you a GDScript object. To get an instance of your class, use the `new()` method of this object :

var my_instance = MyClass.new()

There is no easy way to add constructor parameters, so you can just define a separate initial setter method in your class.