Search code examples
godotgdscript

How do I implement structures in GDScript?


Is there an equivalent of a C# structure/class in GDScript? E.g.

struct Player
{
     string Name;
     int Level;
}

Solution

  • Godot 3.1.1 gdscript doesn't support structs, but similar results can be achieved using classes, dict or lua style table syntax

    http://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/gdscript_basics.html

    GDScript can contain more than one inner class, create an inner class with the appropriate properties mimicking the example you had above:

    class Player:
        var Name: String
        var Level: int
    

    Here's a full example using that Player class:

    extends Node2D
    
    class Player:
        var Name: String
        var Level: int
    
    func _ready() -> void:
        var player = Player.new()
        player.Name  = "Hello World"
        player.Level = 60
    
        print (player.Name, ", ", player.Level)
        #prints out: Hello World, 60
    

    You can also use the Lua style Table Syntax:

    extends Node2D
    
    #Example obtained from the official Godot gdscript_basics.html  
    var d = {
        test22 = "value",
        some_key = 2,
        other_key = [2, 3, 4],
        more_key = "Hello"
    }
    
    func _ready() -> void:
        print (d.test22)
        #prints: value
    
        d.test22 = "HelloLuaStyle"
        print (d.test22)
        #prints: HelloLuaStyle
    

    Carefully look over the official documentation for a breakdown:

    enter image description here