r/Unity3D • u/Enderblaze101 • 9d ago
Question Saving game data to a file?
Hi, I've been (slowly) developing a magic themed isometric farming game. I've spent months and have little to show for it, just a static grid of tiles and basic camera movement, because I can't figure out how to make a save/load system or an updating toolkit UI.
To lay it out, when I launch the game, it needs to check for a save file and load it. If no save file exists, it generates a new one and starts the new game sequence (Player Creation, eventually). Most actions in the game will perform a save action, saving whatever "part" of the game it relates to (Map objects, currency, player stats, etc).
What techniques or processes should I be looking into to achieve this? I've looked at things like JSON and System.Serialisable, but couldn't figure it out from the documentation.
As for the UI, I can't get it to update the display values. It displays preset values and appears to load data from a file, but changing the values doesn't update in the UI, e.g. changing the currency from 100 to 200 still displays 100. Am I using the wrong data field or do I need some intermediary data holder?
Any help will be greatly appreciated, Thank you in advance.
10
u/Artuplabs 9d ago
simple route that works fine for a farming game:
one plain [System.Serializable] class SaveData with public fields: currency, stats, and a List of tile entries (JsonUtility can't do dictionaries, so use a list of small structs). save with File.WriteAllText(Path.Combine(Application.persistentDataPath, "save.json"), JsonUtility.ToJson(data)). on launch check File.Exists(path): if yes JsonUtility.FromJson<SaveData>(File.ReadAllText(path)), if not new SaveData() and run the new game flow. write to save.tmp first and then move it over the real file, so a crash mid write doesn't eat the save.
the ui thing is separate. setting the text in Start reads the value once and never again. keep the data in one object and have it fire an event like OnCurrencyChanged whenever it changes, the ui script subscribes and sets label.text there. or just update the label in the same method that changes the value. it's not the wrong field, nothing is telling the ui to redraw
3
u/MeishinTale 9d ago
You got everything covered here for the base operations.
To go further (maybe after you experiment with the base );
There are Json libs that allow dictionary serialization (most famous NewtonSoft)
You can include a Json into a Json using text/Json ref. For example you have a global Save class with reference to an Inventory (or whatever system). Just hold a string (or a Json ref if your using NewtonSoft) in the global save and let the Inventory system decide what's in its save. The global save only holds the refs to group everything into a final unique file. You can even get rid of the dependencies completely by using a saving interface (string GetSave, LoadSave(string)), so that you write your save system once and never have to change it (just register new systems which implement the interface).
it's good practice to keep at least 2-3 previous files in case something goes wrong when loading the new file. It's also important to detect and act on a save not working properly
1
u/veeavs 9d ago
This quick tutorial got me set up quick.
https://youtu.be/rDZztBWGMIs?is=XQtmTtnnQmD3hzcQ
Some other good stuff in their playlist that might help but if you wanna study deeper it’s something to start. I needed to serialize dictionaries so I added newonsoft.
2
u/Enderblaze101 8d ago
This was actually really helpful. A lot of tutorials rush through or entirely skip the file path and data organizing parts. But this make so much more sense.
1
u/FranzFerdinand51 9d ago edited 9d ago
You seem to be missing a lot of the basics of C# and even if you solve these 2 issues that lack of knowledge is going to hurt you over and over again. I’d recommend taking a weeks break from the game and going over a proper tutorial. CodeMonkey has a 12 hour C# tutorial for free that covers everything you’ll ever need.
2
u/Enderblaze101 8d ago
I've been trying to learn various languages (C, C++, C#, Python, etc) for almost a decade. I find some of the math and geometry side of C# to be more intuitive, but the technical stuff completely escapes me. I've watched all sorts of tutorials and read tons of documentation, but when I try to apply anything I've learnt it just doesn't work correctly and gives no explanation of what went wrong.
2
u/RoberBotz 9d ago edited 9d ago
You can use the easy save library on the marketplace.
I was thinking of writing my own save and load system to use it in all my games, but then I asked myself, why, there are already good ones made, I don't need to make it myself.
I already made this mistake by making my own behavior tree and my own dialogue system, they worked but were buggy and sometimes I had to take breaks from the actual game to fix the dialogue system.
if you get a library, you don't need to do that, if there is a bug you can wait and the one who has the library will fix it.
In my case, I save most of the game data in scriptable objects and save/load them with the easy save library, but only in key moments.
So, the main data stays inside those files, the game updates the data from those files, then in some key moments like loading screens I use the library to save them to file.
Then when the game starts, I load the save file in the scriptable objects, and work with those scriptable objects in-game, modify them, but only save them to the main save file in key moments.
You can create many save files, save only specific values and a lot of stuff, pretty cool.
You could easily spend a few weeks making a good save and load system, in my opinion is better to get a save library.
If you want to make a game, you don't also need to make a save&load library, if you want to make a save&load library you don't also have to make a game.
You need to focus on what your goal is, and focus on that.
1
u/ledniv 9d ago
I think the easiest way to reason about this is to stop thinking of the save file as the game state.
Keep one runtime GameData object that contains the current state of the game: currency, player stats, map state, inventory, etc. When you start the game, either initialize that object for a new game or load values from disk into it. After that, gameplay modifies GameData, not the save file.
Your UI should also read from that same runtime data. So if currency changes from 100 to 200, the gameplay logic changes GameData.Currency, then the UI displays 200. The file is only persistence. Saving means writing the current GameData to disk. Loading means filling GameData from disk. The UI should not be reading the file to figure out how much currency the player currently has.
I would also avoid having a dozen different Save Manager scripts for different parts of the game. Put the state needed to reconstruct the game in one place, then keep the code that reads and writes that state in a separate class. That makes it much easier to understand what is actually being saved.
For the file format, JSON is perfectly reasonable while learning because you can inspect the file. I personally prefer binary once the system is established because it avoids converting the data to text and back and produces smaller files. Whichever format you choose, I would also plan for save versioning early because your GameData structure will change as the game grows.
Small plug: I have an entire chapter on exactly this in High Performance Unity Game Development with Data Oriented Design. It builds a save and load system around separating GameData, gameplay logic, presentation, and the code that writes the data to disk. The following chapter also shows how the UI reads the same runtime state.
https://www.manning.com/books/high-performance-unity-game-development
4
u/gingerbreadmens_ex 9d ago
Serialization is a deep rabbit hole when you first get into it, so don't beat yourself up. The core idea is you have a plain old class that holds all your runtime data (tiles, wallet amount, player stats) and you just convert the whole thing to a string to dump on disk, then parse it back on startup. The mental model that clicked for me was treating the save file like a frozen snapshot of that one data class.
For the UI not updating, you're probably still reading from the file on start but never writing the new value back to the data object that feeds the display. I always keep a runtime copy of the data and make the UI refresh from that single source of truth whenever something changes, otherwise you're just staring at stale numbers.