I dont think I understand custom resources

Godot 4.5

I’m trying to create a kind of item generator/loader script, to store the data of all items in instead of creating unique nodes out of all of them. I think this will be more memory efficient in the long run if I end up with a lot of them, and using data sheets seems intimidating :smiley:

extends Control

@export var item_scene = load("res://scenes/item.tscn")

func get_item(item_name: String):
	var new_item = item_scene.instantiate()
	add_child(new_item)
	new_item.data = get_item_data(item_name)
	print(new_item.data.length)

func get_item_data(item_name: String) -> ItemData:
	var new_data: ItemData
	match item_name:
		"Sword":
			new_data.length = 3
	return new_data

I’m calling the get_item function with the string “Sword” here. The item_scene has the following in it:

@export var data: ItemData

func _ready() -> void:
	data = data.duplicate(true)

So when I go to set the new_item.data, it should have it’s own unique ItemData, which among other things contains length.

class_name ItemData extends Resource

@export var length: int

The error I get is this: get_item_data: Invalid assignment of property or key ‘length’ with value of type ‘int’ on a base object of type ‘Nil’.

To my understanding, that error usually means youre trying to access something that hasnt been initialized yet, but how can that be when I just set new_data to ItemData?

You never assigned any value to that new_data variable, so it’s null. Try this

func get_item_data(item_name: String) -> ItemData:
	var new_data:= Item Data.new()
	match item_name:
		"Sword":
			new_data.length = 3
	return new_data

Then I don’t really see the point of this _ready() function, you should probably remove it:

1 Like

thanks, that works! I thought assigning the type was “filling it” but i see why thats not the case. And since we’re creating a new one, duplicating is not necessary?

No, if you just provide the type, the value is still null. Unless it’s not na Object type, then it will be assigned some default value automatically, like bool type will get a false value.

Correct!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.