How do I implement structures in GDScript?
Asked Answered
K

1

16

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

struct Player
{
     string Name;
     int Level;
}
Kan answered 7/5, 2019 at 12:25 Comment(2)
I accepted it the day you answered, thank you for the help :) Is it not appearing for you?Kan
So silly of me! I'm using a new browser extension to change pages into 'dark mode' and forgot to turn it off for stackoverflow. The checkmark was showing gray for me, even though it was actually green. I will delete my original comment. Thank you!!Washington
W
33

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

Washington answered 7/5, 2019 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.