Saving and Loading inventory with Item.new()

I’m making a save/load system using Json and I’m trying to load my inventory which is just an array of the item class .new(), and it doesn’t work and crashes the game. For example:

var items: Array = [
DullDagger.new()
Egg.new()
Egg.new()
]

would be my inventory. How could I make it so where instead of saving the node identity, I make godot save it to be literally DullDagger.new() so when loading the game doesn’t crash?

You’re going to need a lookup table and a case statement.

func create_object(value: String) -> Node:
	match(value):
		"DullDagger":
			return DullDagger.new()
		"Egg":
			return Egg.new()

Oh so I should save the class name and do that instead of that? So I don’t have to change my inventory system but instead save the inventory as their class name then? Doing that, is there an easy way I could store the class name of each entry of the array rather than it, or do I have to make a function that does that?

There’s no way to turn text into code without a conditional statement testing the text. Not that I know of anyway. In fact what you’re trying to do is introduce the vulnerability of code injection that people are always worried about with the ResourceLoader. This would be a lot easier if you just used Resources to save and load your objects because it would handle all that for you.

As I already said in your previous question, just use a custom resource class. It will make your life much easier during the development. You can always add serialization of that resource into a json (for whatever reason) later when the game is nearer to the finish line.

Otherwise, you’ll constantly need to cater to that json reading/writing whenever you alter something in your save data structure.

2 Likes

I agree with @normalized. I do the same with a multiplayer game I’ve been working on. When it came time to transmit data through RPCs, I had to turn them into dictionaries. So I created a from_dictionary() and to_dictionary() functions. This allowed me to also serialize the data to JSON quite easily.

2 Likes

Yeah, I was worried about “what if someone downloads a save file with malicious code” but It’s so unlikely unless you’re like a world renowned game developer, and even then you have to download it. It’s honestly not that big of a risk. I’ll honestly just do that, thanks.

3 Likes

Smart choice :wink: