Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement structures in GDScript?

Tags:

godot

gdscript

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

struct Player
{
     string Name;
     int Level;
}
like image 984
Max Avatar asked May 07 '19 12:05

Max


People also ask

What does := do in GDScript?

Got it! := may be used in the line declaring a variable to set its type.

Does Godot have structs?

Structs. Structs (from GLSL) can finally be declared in your shaders! This change was also ported to Godot 3.4 by @lyuma via #48075.

Are there classes in GDScript?

Classes describe an aggregate of ta fields such as variables and defines the operations, such as methods. Think of a class as a blueprint for creating objects, with initial value states, and implementation behavior. In GDScript, by default, all script classes are unnamed classes.


1 Answers

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

like image 138
Dayan Avatar answered Sep 19 '22 12:09

Dayan