Welcome, Guest. Please login or register.

Login with username, password and session length

 
Advanced search

1412192 Posts in 69756 Topics- by 58693 Members - Latest Member: NebulaFlare

January 24, 2025, 04:30:00 AM

Need hosting? Check out Digital Ocean
(more details in this thread)
TIGSource ForumsDeveloperTechnical (Moderator: ThemsAllTook)How do you save a list of instances of a class and make it readable? (C#)
Pages: [1]
Print
Author Topic: How do you save a list of instances of a class and make it readable? (C#)  (Read 1261 times)
jmas
Level 2
**


View Profile WWW
« on: December 14, 2024, 12:09:18 PM »

Basically I'm trying to save an inventory(list of items(List<Item.cs>)) and load it. But when I save it to JSON, it comes out as:

{"Items":[{"instanceID":-39626},{"instanceID":-39660}]}

Here is my code:

SaveLoad.cs: https://pastebin.com/P65ka5WS
Saving it in another class: https://pastebin.com/4QJ1djHr
Itm.cs: https://pastebin.com/yEjAKGTD

I'm using this really helpful class called JsonHelper someone made here's the link: https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity

Here's the tutorial I was following if it helps:



I've been researching and googling how to do this and I don't understand anything I find this video I just shared is the closest thing to understanding I could get all for it to not work for me

Extra information: Sometimes I have items(Itm.cs) in my inventory that are inheriting from Itm.cs so for example I have a weapon or shield(WEAPON.cs or Shield.cs) that inherit from Itm.cs. And they both have a bool called "equipped." Will I still be able to save the list of items?

Thanks in advance
« Last Edit: December 14, 2024, 12:16:34 PM by jmas » Logged

michaelplzno
Level 10
*****



View Profile WWW
« Reply #1 on: December 15, 2024, 11:49:11 PM »

Not 100% sure but try making item a struct instead of a class.
Logged

Eb3yr
TIGBaby
*



View Profile
« Reply #2 on: January 13, 2025, 02:39:59 PM »

I wrote this big response with some demo code about using System.Text.Json for this before I realised that 1) this is Unity and is stuck back on old .NET versions, and 2) Unity's JsonUtility.ToJson method has an optional boolean parameter called prettyPrint that's false by default. Just pass in true after the object to be serialized and you should be good. Do you still need that wrapper for arrays in modern Unity from the stack overflow question you linked? I would've thought by now that their serializer would be able to handle arrays.

On the inheritance note, so long as you use the generic for that specific item class, you'll be fine. For example JsonUtility.FromJson<Shield>(jsonString) will include the equipped field, but JsonUtility.FromJson<Itm>(jsonString) will not.
Logged
Pages: [1]
Print
Jump to:  

Theme orange-lt created by panic