Why is my singleton being changed?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By lukesheep

So i have a singleton with information about skills and how many times it can be used.

skills[0] = GameData.SkillData[GameData.heroSetUp[char_name]["Basic"]]

During the battle, i change the number of uses inside the local variable, but it is changing the singleton value. Why is that?

:bust_in_silhouette: Reply From: Zylann

Note that arrays and dictionaries, like objects, are passed by reference.
So when you access an array from your singleton and store it in a local variable, if you modify the values inside it, that will reflect into your singleton because your local variable stores a reference to that array, not a copy of it.

Basically:

var array = [1, 2, 3]
var temp = array
temp[0] = 42
print(array)

will print:

[42, 2, 3]

If you want to have a copy in your local variable instead, use duplicate() like so:

var temp = array.duplicate(true)

Note: true means if the array contains nested arrays/dictionaries, these will also be duplicated, assuming there is no cyclic reference in your data Array — Godot Engine (stable) documentation in English

The code you posted doesn’t really show what you’ve done, I don’t know how skills got an array inside it originally so it’s hard to tell if you made that mistake. I would check what I described, though, because it’s a mistake I see happening from time to time.

Thanks a lot, that was it. I get it now.

lukesheep | 2020-04-30 10:49