+1 vote

I have this class and I want to make a dictionary of it

class Building:

    # building type
    var type : int

    # building texture
    var iconTexture : Texture

    # resource the building produces
    var prodResource : int = 0
    var prodResourceAmount : int

    func _init (type, iconTexture, prodResource, prodResourceAmount):
        self.type = type
        self.iconTexture = iconTexture
        self.prodResource = prodResource
        self.prodResourceAmount = prodResourceAmount
    func _ready():
        var base = Building.new(0, preload("res://Base.png"), 0, 0)
        var mine = Building.new(1, preload("res://Mine.png"), 2, 1)
        var greenhouse = Building.new(2, preload("res://Greenhouse.png"), 1, 1)
        var solarpanel = Building.new(3, preload("res://SolarPanel.png"), 4, 1)

I had copied it from a tutorial and now I want to convert these four building's attribute into a dictionary. please tell how can i do it

Godot version v3.2.3-stable_win64
in Engine by (942 points)

1 Answer

+1 vote
Best answer

Is it?

Dictionary syntax:

var _dict = {
    "keyName": value
}

For your example:

var _dict = {
    "type": null,
    "iconTexture": null,
    "prodResource ": 0,
    "prodResourceAmount": 0
}

...

_dict.type = object.type
# or
_dict.type = 10

UPD

Okay, I found other solution. You can dynamicully get class'es properties and set them in dictionary

var b = Building.new(...)
var _dict = {}
for i in b.get_property_list():
    if i.name != "Reference" and i.name != "script" and i.name != "Script Variables":
        _dict[i.name] = b[i.name]
print(_dict)

Read more:

by (102 points)
selected by

Thanks! It is helpful but can you tell the reason of the if statement below for

This values returns with your properties (are they Godot's system?) and we should remove them from our dict.

Don't know. I just want to know the reason why we used that. I don't know what are they and why we used them

I answered here:

This values returns with your properties

Is it all what you want to know?

Got it!
Thanks :)

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.