How to insert a unique scene into an array?

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

So i have first inventory scene with item slots array

extends Node2D
onready var itemscene = preload("res://src/Items/Item.tscn")
var item
export var inventory = [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ]

func _ready():
	inventory[28] = additem()
	inventory[28].itemdata.type = "test28"
	inventory[29] = additem()
	inventory[29].itemdata.type = "test29"
	print(inventory[28].itemdata.type)
	print(inventory[29].itemdata.type)
	pass
func additem():
	var inputitem = itemscene.instance()
	return inputitem

Then i have item scene with dictionary

extends Node2D
var itemType = ["armor","weapon","trincket","other"]

export var itemdata = {
	"type": "weapon",
	"damage": 10,
	"attackSpeed": 0.4,
	"strenght": 1,
	"intelect": 1,
	"dexterity": 1,
	"texture": ""
}

but when i changing scene in one array’s slot all other slots are changing too
enter image description here

I had once this type of issue. Try if it works when itemdata is not exporttype

Inces | 2022-08-24 20:28

Actually works. Thank you very much

hrp | 2022-08-25 06:13

:bust_in_silhouette: Reply From: Lopy

When you write export var itemdata = {...}, all instances will share the same Dictionary. This is the same for other reference passed things like Array or Objects, but not most built in types like int or String.

To avoid this, you can remove the export, or assign the value later:

tool # To have the _init function run in the Editor
extends Node2D

export var itemdata: Dictionary


func _init() -> void:
    # Avoid overriding itemdata if we where loaded
    # and are not new.
    # (itemdata is set to an empty Dictionary when
    # we are created in the Editor)
    
    if itemdata.empty():
        itemdata = {
            "type" : "weapon",
            #...
            
        }

With the above you get an exported Dictionary that is unique for each instance.

Note

You are also sharing your inventory with export var inventory = [null]. I recommend you write:

export var inventory: Array

func _ready():
    if inventory.size() < 30:
        inventory.resize(30) # Fills empty spots with null

PS

Sharing variables across instances is very useful to make “static” variables. Sadly is it not very intuitive and seems undocumented.