Simple Saving and Loading with JSON to a File (Unity Tutorial for Beginners)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello and welcome I'm your code monkey in this video we're going to learn the simplest way for saving and loading data in unity using JSON as our file format let's begin so here is our scene that we've been using to test saving and loading there's a player character in here I can tell him to move around and town to mine these notes as you can see the goal mount increases the goal is to save the gold amount and player position so first we set up saving and loading using the player breaths which is a very simple way of storing persistent data in unity then we looked into saving and loading using save files we'll learn how we can write and read text from a file and how to create our own file format to store multiple values now in this video we're going to use JSON instead of our own file format if you're interested in what is JSON and how its formatted you can check out my previous video that goes into the details of the JSON format so let's check out the code here in the game handler we have a save and load function we're currently set up to save using a save file first we grab all the data that we wish to save we store it in a temporary string array we join that array using our safe separator which is a constant defined up here then with the final save string we simply save it into our save file now instead of doing it that way we want to use the JSON utilities functions that are part of unity to serialize and deserialize a save object so let's begin by making a save object and seeing how Jason works in unity so let's go down here and in here we're going to make a private class and let's call it save object this won't contain all the data that we wish to save so for now let's just make a polygon for our goal I'm not alright let's leave it at that just for starters let's go up here onto our awake and in here let's instantiate the class with a certain amount of gold make a save object save object equals in you say project and we're going to set the goal amount to let's say 5 now let's see realize this object to do that we're going to use JSON utility dot 2 Jason this receives an object which in this case our save object this function as you can see returns a string which is the json representation so let's make a string chase which is our Jason text now let's simply print it out it with the bug log of our Jason string and see what happens all right as you can see in here we have a correct JSON representation of our save object you can see that it stored the gaunt amount as five all right so we can now convert a save object into a JSON string now let's do the reverse so let's take our JSON string and convert back into another save object for that we're going to go again into the JSON utility and now we're going to use the from Jason function this function is a generic so it takes the type of object that we wish to load which in this case is a save object and then we receive the JSON string so that and this whole thing won't return an object of type save object so save object let's say loaded save object so now let's do a print on the unloaded save object dot goldimouse so debug log of the unloaded gun amount which should return five so let's see yep there you go the first one has the JSON string containing five on the gold amount then the second one loaded that string into a save object and the save object now contains a gold amount of five so now that we know how to convert to and from Jason let's apply that to our save and load functions now first we need to go down here and expand our save object wants to store a vector three for our player position so a public vector three for our position previously we were storing the X&Y separately but since we're using Jason we can easily just serialize a vector three making our save found much simpler so now let's go up here on D save and instead of creating all of this string let's erase this and in here we're going to create a save object which won't be a new save object and we're going to set the fields of the gold amount to the bond amount that we defined up here and also the field for the player position to our player position all right so our save object now has only correct fields now again do this thing that we did up here to get the JSON string based on this save object then we take that JSON string and that's what we used to save in our save file so let's run the code and see Farsi file now correctly contains a JSON string Here I am let's go down here mine a couple of gold so one two three and now let's say move in here and now hit C there you go he's saved now let's check out the save file as you can see the save found contents does indeed contain a jason save string so now that saving is working let's set up the unload function so here on the unload first we are correctly unloading the save string by reading all the text okay that is correct now we're no longer going to have the contents as a string split but it said as a save object so we're going to use JSON utility dot from Jason we're going to use the save object object type and we're going to use the save string that we loaded from the file this will return a save object now we can erase all of this and we're simply going to use the save object that in this case set the position to the player position and going to the save object and set the goal amount so we are loading our data based on a string stored in our save file we convert that into our save object and then we unload the correct data into our game all right so let's run the code okay everything is on default he's on zero zero with zero of gold and now if I hit load yep there you go he went in there and now he has three gold which is exactly what we saved so we now have our C system working with a very robust and standard file format now let's just make this a bit more robust and make a say file folder that can handle multiple save files we're going to make it automatic to create the folder if it doesn't exist yet so let's go to our game Handler and on our awake we can remove our testing code any here and let's do a test if the directory does exist so we can go up here we know I'm gonna need this save string so let's set a private cons string for our save folder and we're going to the same thing that we use down here so application dot data path that gives us the data path of our executable so in here on let's add another slash and let's say saves this will be our saves folder now as you can see this contains an error since application of data path is instantiated at runtime therefore it cannot be a constant so we can suddenly solve this by making this a static read home and okay we have essentially a constant but that is set on runtime okay so now down here before we do anything let's make sure the folder does exist so in here do I if directory that exists directory is part of this system I own namespace and in here let's just STP say folder does exist if it does not exist then we need to create it so we do directory that create directory of our save folder all right so now on our save down here instead of using application not data path we're going to use our save folder now in order to keep our code clean let's copy all of our safe system into its own class so let's go in here and make another script and let's call it save system now in here this won't be a simple class so no mana behavior and let's make it static so we never instantiate this class so here let's start with a public static void init function to initialize the safe system which is what we're going to call in here so do a safe system dot in it now in there and leches initialized by testing the safe folder and let's copy this a folder into there of course we need a peer using system uh-oh ok so now we need a public static void for our save and now in order to save we're going to receive a string for our save string and then we're going to have a public static string for our load which will return a save string so in here let's copy the file dot write on text into there so in here we're going to do safe system dot save and we're going to save sending our JSON string and in here we're going to save into our C file using Power Save string so for the unload we're going to have our say string which will be from the safe system that load and here if you cannot load anything then tone which are known so let's simply do if save string if it is different from no then we're going to Odin like normal so let's copy all this into our load so in here we test if the save file does exist if so we return the save string if the phone does not exist then let's return no okay back in the game hammer in here everything is correct we ask the safe system to return our safe string then we test if it is not known then we unload the correct object and only say we are telling the safe system to save and we're sending D Jason strength so now our code is nice and easily separated so let's run the code and see if everything is working exactly as previously okay here I am one zero zero and it found load it says no save since there is no save on the me only created save folder you can see we have the saves folder automatically created and it is currently empty so let's try to save and see if a file is spawned in there so let's go - ok - now let's save save and there you go there is now a file on these safes Wanda we can erase the old file so now there we have a safes folder that is automatically created let's save multiple files so in here on our save function instead of always saving into the same file let's save into a different file so in here on let's make it a simple int for the save number and let's start at save number one and now in here only simply do a while file dot exists and we're going to call the file save then we add the save number and then we add dot txt so if there is already a file with that same number then we're simply going to increase the save number save number of months so essentially this one will continue running as long as the save number already exists so when we exit this while we know that the save number is unique so let's save using that so save was the save number plus dot text okay so let's run the code is see if various saves are created so here I am and I save and here I hit refresh and there you go there save one now I save again hit refresh and there you go now we got safe to save again now we got save three all right so we are now currently saving without overwriting now let's setup the unloading we want to automatically load the most recent file so let's go into our load function and in here we want to get the list of all files in our safe folder so for now let's create a directory info which is a new directory info using our save folder and now we can use the directory info get files which will return an array of file info ok so we now have all of our safe files now let's second through that array and in here and let's locate the most recent file so let's go here make the file info for the most recent file let's know and in here file info doc last right time if this one was written after the most recent found out last right time then this one is more recent so the most recent becomes this one and down here if the most recent file if it is not known that means we have a file to load and in here we're simply going to do the same thing we did down here except instead of loading from saved text we're going to load from the most recent file and in case we do not have a most recent funnel we're going to return no okay great so our load function we first created the rectory info which is allows us to do various things with the directory so we create one using the say folder path then we get all the files that contain that text which is the format that we're using for our say files but it could be anything so we get a list of our C founds we cycle through the list of save files and we set the most recent file so if we have none then set this one if we do have a most recent file then select the one that is most recent the one that has the highest last right time then down here we simply check if we do have a most recent file then we return the string that is loaded from that file if not then we simply return no so this function is now correctly returning the most recent file so here I am in the game and now we find it l yep there you go with loaded the previous file so now let's go up here and blow it again okay he's still loading in there now if I go in here and I hit save now I move away and now if I hit L I shouldn't load in here instead of in here so hello and there you go and one of the most recent fun now I can go in here and manually delete the last file so say for get rid of that one and now if I hit load I wouldn't be down here instead of back up here yep there you go so there you have it we took our saving and loading from before and instead of making our own file format we use the JSON format since it is very robust and easy to use then we added support for automatically creating a folder to store our C files and save multiple files one loading from the most recent one as long as you can download the project files and utilities from unity code monkey comm if you have any questions post them in the comments and I'll do my best answer them subscribe for more videos and I'll see you next time you
Info
Channel: Code Monkey
Views: 80,808
Rating: undefined out of 5
Keywords: unity save load, brackeys, unity tutorial, unity game tutorial, unity tutorial for beginners, unity 2d tutorial, unity 3d, unity 3d tutorials, unity tutorial 2d, unity game, unity 2018, beginner, easy, unity2d, unity3d, unity, basics, basic, game dev, code, programming, clean code, unity clean code, code monkey, how to, learn, tutorial, course, game, game development, to, how, series, tutorials, games, coding, unity save, unity save game, unity saving data, unity saving, unity saving game
Id: 6uMFEM-napE
Channel Id: undefined
Length: 15min 15sec (915 seconds)
Published: Fri Sep 14 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.