Methods in GDScript

GDScript supports methods defined on custom types. Here’s an example demonstrating this concept:

extends Node

class_name Rectangle

var width: int
var height: int

# This area method is defined for the Rectangle class
func area() -> int:
    return width * height

# Methods can be defined for any custom type
func perim() -> int:
    return 2 * width + 2 * height

func _ready():
    var r = Rectangle.new()
    r.width = 10
    r.height = 5

    # Here we call the 2 methods defined for our custom type
    print("area: ", r.area())
    print("perim:", r.perim())

    # GDScript doesn't have pointers, but you can pass objects by reference
    # This is similar to using a pointer in other languages
    var r_ref = r
    print("area: ", r_ref.area())
    print("perim:", r_ref.perim())

To run this script, save it as rectangle.gd and attach it to a Node in your Godot scene. When you run the scene, you should see the following output in the Godot output panel:

area:  50
perim: 30
area:  50
perim: 30

In GDScript, all variables are references to objects, similar to how pointers work in some other languages. This means that when you assign an object to a new variable or pass it as an argument, you’re working with a reference to the same object, not a copy.

GDScript doesn’t have the concept of value types vs reference types for method receivers like some other languages do. All method calls in GDScript are effectively on references to objects.

Next, we’ll look at GDScript’s mechanism for defining interfaces, which in Godot are implemented using abstract classes.