🌐 Have you found the videos Helpful and Valuable? ❤️ Support on Patreon www.patreon.com/unitycodemonkey or get the Game Bundle unitycodemonkey.com/gamebundle.php
*Question* How do you use this to save multiple different systems? *Possible Answer* Each System would have it's SaveObject and a function that returns a JSON string, then you would have a master SaveObject that would contain multiple string fields for storing each system JSON save string. You would then save the final JSON from that object into a save file. For loading you would load that master SaveObject and then use the stored JSON save strings to load all the other systems.
Dude! This tutorial was awesome! Words cannot express my gratitude for unwrapping a topic that had been driving me crazy so simply and precisely. Thank you!!! :D
This is the best tutorial I've seen in a long time, thank you! You explained how everything worked really thoroughly yet also simplistically. Thanks for the help!
If you cant see your file generated under your project folder name try to replace Application.dataPath for Application.persistentDataPath. it worked for me. it will looks like: File.WriteAllText(Application.persistentDataPath + "/saveFile.json", json);
Great tutorial! Is JSON + IO better than playerprefs in terms of performance? If I have to save settings, what's the best way? JSON or playerprefs? thanks.
You can use JSON in PlayerPrefs as well, its simply a string.Normally I store game settings with PlayerPrefs (Resolution, Keybindings, etc) and game state with save files. Cheers!
5.42 : File.WriteAllText (Application.dataPath + "saveFile.json", json); 5.55 : File.WriteAllText (Application.dataPath + "/saveFile.json", json); Good joke :) After a few questions about this code that was not working, I was able to finish the video. Jason is a nice, accommodating little guy ...
@@CodeMonkeyUnity Same on the September video: there are stealth slashes (and even SAVE_FOLDER). In any case, I learned a lot of things (in particular to be wary of data coming from outside ^^). Thanks, I hadn't really messed with the filesystem ...Great moment of solitude ...
How would you securely save data using json? Should you encrypt the string and if so where would you store the key in order for it to be decrypted on load again? Great video btw!
strings are just bytes so you can encrypt them with any algorithm you want. But if you're making a game, don't bother with trying to encrypt the saves, it's not worth the effort. If it's a multiplayer game, then store everything in the servers.
I have several videos coming up regarding a save system so stay tuned for those. But just based on this video you can easily expand the PlayerData to add some fields for whatever you wish to store there. For an Inventory System you could define your items with an enum and store it easily. private enum Item { Dagger, HealthPotion, } private class PlayerData { public Item itemSlot1; public Item itemSlot2; }
I'm working on a couple of videos making a Save System, JSON will be used as a simple way to serialize a SaveObject. I've not used other serializers, I either use JSON or bytes. In a more advanced Save System I'm going to cover how to directly save bytes into a save file and embed a screenshot. Cheers!
This is an example taken by wikipedia. How can you access the postalCode field, and the type of phoneNumber? { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ], "gender": { "type": "male" } }
Its all about creating objects that match that pattern. So in that case it would be this public class SaveObject { public Address address; public class Address { public int postalCode; } } Then you would access saveObject.address.postalCode;
Is it possible to save data to a JSON file and copy then paste the JSON file to another device that has the same project (in a build) to open the JSON file up there (in the build) and have all the data? I’m making a level maker for my game and would like a way of copying the JSON file so others can open it up in the build.
Code Monkey at around 5:43 you said about seeing if saveFile.json will show up after putting in that code.I tried what you did and that file didn't show up. I'm perplexed by this because to my knowledge changes to the actual project data only appear during runtime or in the actual build of the project and those changes are reversed after the project has stopped running in Unity. Seeing the text added to the json file outside of running the project does remind me of an old idea I had. So, If anyone else is confused about this; I created a saveFile.json in my project folder outside of unity and set an absolute path to that file because mine isn't in the base Asset folder and now it works. This video is a good start to learning how to use json and I did learn from this.
The runtime memory data does get wiped as soon as the game shuts down (data stored in variables) but an external file is not automatically deleted. Maybe you have some permissions issues. Add a Debug.Log to see where you're saving the file and what response the WriteAllText(); gets.
@Bebe Agachevo If File.WriteAllText(); doesn't throw an exception then it successfully made the file. So if you don't see any errors then chances are you're not setting the path correctly so it's being saved elsewhere. Try a simple path string path = @"c:\MyTest.txt";
Nice video! Thanks for showing how to use JsonUtility inside C#.I know that it's possible to use the Json file to "send" the data to some DataBase like SQLite or MongoDb. But how could we lock or cryptograph the data inside Json, so clever and curious player's like us couldn't get inside it, giving ourselves infinity Health, Bullets, God mode, all cards available, etc... ?
In a singleplayer game you really shouldnt waste time trying to stop cheating, better spend your time making the game better In a multiplayer game you should never trust the player for anything so that would require a different design
No, you can only store anything that can be converted into text so a reference in memory cannot be stored directly. You can store the type of game object (like if it's a type of weapon or something) or the object position and use that on loading. I handle saving and loading here th-cam.com/video/6uMFEM-napE/w-d-xo.html
Can you do an item database tutorial? Idk if I should stick with JSON, Regular Script initialization or serialized Scriptable Objects. I need some insight... Ive tried both and Im still unsure which way is better
It's tough because I'm using my custom animation system. I did do some videos on the base of that animation system, check out the videos on how to create and modify a mesh through code, that's the core of the whole system. Cheers!
I don't think there's any way to create a new class structure just with Bolt. But you can make a very basic C# file just to define the structure and then use it with Bolt
JSON stores key-value pairs so it needs a field to know the name of it. So yes you need a class/struct to hold the data, I don't think JsonUtility.ToJson(); works, although I never tried that myself
@@CodeMonkeyUnity confirmed that not works, i hace tried un that way but ir doesn't understand the strings so give an insanely big value(something like 1211111000).Thanks for the answer!!, just to mention contrats for tour c# course on teachable, i already finished it is really complete
I liked how you went into detail on how to do it, but I would like some help understanding how it does what it does, I'm just starting to make a practice app, and my friends wanted to make a dating sim. So naturally I have to learn how to make a save and load file system. I just need a little more help. Please and thank you.
JSON is a file format, what it does is really just type conversion from whatever type into string and back again. Tehcnically the JsonUtility uses Reflection to find the class member fields and uses System.Convert to do all conversions.
I'm having trouble with arrays within the JSON object. I've found that JSONUtility isn't so good with handling that, still trying to make this wrapper solution I've found on the forum to work but no luck. Wondering if you have had similar problems with array within a json object
I'm not all that familiar with JSON, however I noticed when it's saved in a file it's all on one line, is there a way to format it so it takes up multiple lines and is more human readable?
JSON is easy to make save and loading, but it's really easy to read which also makes it easy to modify, so a more better way of doing this is binary. Because their binary thier really hard to read which also make them very hard to modify.
Hey, i know this is a fairly old video, i wonder if you have any newer ones... I wonder if you could answer a question for me... How does one go about assigning a super complex JSON to an object without making a bunch of classes? For example, I have one I'm working on with a client, and the JSON being downloaded via an API get request he has me working with is like... "data": { "mainMenuConfig": { "booksConfig": { "content": [ { "title": "", "category_items": [ So, the only way I can figure out how to assign this is make an object for data, for mainMenuConfig, for booksConfig, for content, and for category_items, so 5 objects in total(most pointlessly holding another object lol, even the "title" variable isn't being used)?! I wonder, what is the point of these nested objects? lol, why does mainMenuConfig not just contain the "content"? But, that's besides the point, would you happen to know an easier way to assign these values without making a bunch of objects? FYI i need the Data because it actually contains another object further down(i just didnt want to make this comment gigantic lol). But it took me like 2 hours to get all the values assigning... i wonder if there's a more efficient way to do this? Besides creating 5 useless classes to hold all this info lol, this isn't the first time I've come across overly complex JSON files containing seemingly empty, useless objects that just hold another object lol. I tried using JsonNode as well, but that just makes it so you have to assign each value manually and it makes the script look kinda sloppy...
Visual Studio has an option for "Edit > Paste Special > Paste JSON as Classes" which automatically creates the classes for you Alternatively you can look into the dynamic C# keyword, although I haven't used it myself docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic Questions about the structure of the JSON really should be asked whoever made that JSON, only that person knows, maybe they have a good reason for those empty containers, or maybe it's just bad code.
@@CodeMonkeyUnity Ohh, I didn't know of that paste JSON as Classes option. I once did a job for a client where i was just making like 10+ different classes out of JSONs, I was just pasting them one by one, erasing the values and turning them into variables, it took forever, that would've saved me a ton of time haha Thanks for the help! I'll read that doc too to see if i can use that.
Very good tutorial, thank you. I saw your reply on a comment below saying that you wouldn't consider JSON as a "safe" way to store data. It is very easy to crack/access it for android apps for instance (i.e. quick editing it to hack the game). I know you wouldn't store anything really worthy on it but I'm just wondering if there's a better/safer way to keep players from cheating/bugging and keep things a little less exposed. I can't see how json would be better than making a proper encoded save system and using the cloud/database system on the platform you are using (firebase/steamcloud/google services/etc). Thank you!
The only way is to keep your secure data on a server and only give the player limited read access. If the player is in possession of the data then you should assume they can manipulate it. But for the most part I would say don't bother with people cheating in your games unless you're making something multiplayer.
Performance wise, would it be good to use json to save every 10 minutes or so with a bunch of info like in a city builder? And can i save/load json with Jobs if performance is an issue?
Sure a autosave every 10 minutes should work just fine, worst case scenario is your game hangs for a second but if its only once every 10 minutes it's unlikely anyone will be bothered by it. I wouldn't bother jobifying the save code, it's not an issue unless for some reason you needed to save every second.
don't like necro threading but i tried using this and the file is not creating. i have a debug that shows string json is set to the data i expect but file.writealltext isn't writing to the file. This vid is 5 years old but did they change anything about how this needs to work since then or am i just missing something? *edit* Found the issue reading a different comment. There was a missing \ before saveFile.json but it was there after coming back from saving the file. works now!
heh yeah this has happened to me several times, always add a Debug.Log to verify you are saving exactly where you think you are to make sure you're not forgetting a /
despite making the PlayerData class when I save PlayerData playerData = new PlayerData(); it sais playerData does not exist in the current context. It's like; I know that's why I'm making it :S Before this, is it wise to create that variable in Start along with the save and load code? Shouldn't they be their own functions that you can call in your game?
Sounds like you instead wrote new playerData(); and the type is named PlayerData not playerData, remember that everything is case sensitive. As to when you do that, yes in a proper game you would hook the load logic to some kind of UI button click and not on Start unitycodemonkey.com/video.php?v=6uMFEM-napE
What if someone forging our json file manually and accidently delete some string & value. It could give some kind of error in the game, isn't ? Do we need some try-catch in our code or something or maybe set default value in that private classes ?
What would be the process for saving for example a list of custom classes, that each contain list with additional custom class? What happens for me is, it only creates json with reference ID, which I actually don't need. I need the data from the classes in those lists, but I'm unable to get/save them.
That depends on whatever you have running on the server. That class is just for doing a HTTP request unitycodemonkey.com/video.php?v=Gk0-amfn5DM What you do on the server depends on what you have in the server, could be a simple PHP script recording the incoming input onto a database
That is working as expected, enums are really int's with fancy names, so the serializer is doing exactly as intended. If you convert it back you will see the enum value again. Lists also work, perhaps you're trying to save a list with a custom data type? If so you need to make sure that custom data type has the attribute [Serializable]
For days I have been trying to do such a simple thing as to write in the form of text on the screen the content loaded from the text file. All that works for me is writing this text to the console via debug. YT tutorials do not work because they do not take into account Text Mesh Pro. When I try to get help on websites for unity users, discord or forum, I only get "advices" to check my code thoroughly and fix it myself. I really have no more strength.
TextMesh and TextMeshPro works pretty much exactly the same, you just set the "text" field with the text you want, that's it. For reading the file you just use File.ReadAllText();
@@CodeMonkeyUnity no its not the same, you need to use using TMPro; and use TextMeshProUGUI thing, but when i try its breaking a script i dont know how to make it work, maybe by change text from the file to string variable and use this variable in visual script to change meshpro text but i try this for days and cant do it.
Если присмотреться, то этот способ очень хорош для сохранения больших объектов, не разбивая на составляющие, как я это делал используя PP. Урок мне понравился..
Is there a way to duplicate the json files? I want to create a json file everytime I start the game. This only updates de json file if it changes. How do I do that?
What do you mean parsing speecific response key? You mean contacting an API? That's going to depend on what API you are dealing with. Usually you don't have to manually parse anything, as long as the field name and type match.
@@CodeMonkeyUnity yes that tutorial. Without using their party library. Most tutorials are only about saving and loading file. Need Jason rest API receiving method
@@CodeMonkeyUnity Thank You for your response. I have parsed the JSON and stored the string URLs value into 3 different string variables Link1, Link2, and Link3. After that, when I am Passing those string values using start coroutine as its actual parameters (for example : StartCoroutine(DownloadImage(Link1,Link2,Link3)); to download images using WWW then It is giving me an error message " *uriformatexception: uri scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character* ". I probed Unity Answers and Asked question about my problem but didn't get response from anyone. I wonder why it is giving me this error even though the string contains valid URL starting with *https* ://. I apologize for this lengthy reply but I want to get rid of aforementioned problem.
@@CodeMonkeyUnity Suppose, I have a json file like this, [ {object 1 : [91,23,65]}, {object 2 : [44,23,85]}, {object 3 : [27,63,55]}, {object 4 : [25,33,25]}, {object 5 : [52,93,65]}, ] >> So I was asking that can I create objects with given x,y,z co-ordinate using that JSON file?
@@tareqmahmud3902 You can create objects with the saved data, if you use them, but JSON cannot create objects on itself. It's just a method to save data like string, boolean, integer and anything you can convert into a text.
Copy it into whatever object you're converting into json, check out these videos th-cam.com/play/PLzDRvYVwl53vRrMuPBkNNZUmnl1jCHcHs.html Just add a field in the SaveObject
Yes JSON is intended to be easy to read and write so it's not suitable if you're concerned about security. But unless your game is online or extremely specific I wouldn't worry about people hacking their own single player save games.
You need to reference it in some way, maybe store the sprite's name, maybe a GUID. Alternatively you can serialize an image with base64, I actually covered how to include a screenshot in your save file here unitycodemonkey.com/video.php?v=dqySkMFieHE
Well it depends on what you're doing but JSON is much cleaner and much more supported pretty much everywhere. I wouldn't recommend XML unless you absolutely have to.
🌐 Have you found the videos Helpful and Valuable?
❤️ Support on Patreon www.patreon.com/unitycodemonkey or get the Game Bundle unitycodemonkey.com/gamebundle.php
I watched this video while in bed, don’t even have Unity open, and it makes sense. Thank you very much! I’m excited to get my game started
Haha same here , I am in bed and watch your comment 🤣
Me too
I have the laptop in bed and i am on the floor!
Yup, me too. Couldn’t sleep, maybe watching this helps me, but so far no luck 😂
*Question*
How do you use this to save multiple different systems?
*Possible Answer*
Each System would have it's SaveObject and a function that returns a JSON string, then you would have a master SaveObject that would contain multiple string fields for storing each system JSON save string.
You would then save the final JSON from that object into a save file.
For loading you would load that master SaveObject and then use the stored JSON save strings to load all the other systems.
The speed in which you typed "GameHandler" was incredible. You bow to no-one sir.
Dude! This tutorial was awesome! Words cannot express my gratitude for unwrapping a topic that had been driving me crazy so simply and precisely. Thank you!!! :D
This is the best tutorial I've seen in a long time, thank you! You explained how everything worked really thoroughly yet also simplistically. Thanks for the help!
I'm glad you liked the video! Thanks!
This is thee JSON video I needed thanks for making this!!
Awesome! I'm glad you found it helpful!
Man you are Genius and best unity teacher thank you 🙏
Just what I was looking for. Thanks!
In 5:33, You forgot to put "/" in line 18 before "savefile.json". Oddly, in 5:54, the "/" appears in line 18.
One of the top 10 plot holes of all time.
You know this man a highly edited videos to make them seem fast 😂
can we get some pining over here?!
the tutorial has to be in perfect condition buddy xD
This comment helped me immensely xD
Thanks, I've been wondering about this subject for a while
Super useful, much easier than the binary formatter system that I was initially advised to use. Thanks!
HEROE!
Antes no entendia nada nadita del JSON, ahora que he usado varias apis y vuelvo a buscar tutorial (Este), si lo entiendo muy facil!
Hugo "Code Monkey" Cardoso understands your comment, as he is Portuguese himself.
This is the best tutorial I ever seen.
I'm glad you liked it! Thanks!
You are an absolute god!!! Thank you for this video!!!! You saved me!
I'm glad it helped! Thanks!
bro that was super useful thanks for the help I really needed it
Just what I needed, thank you!
If you cant see your file generated under your project folder name try to replace Application.dataPath for Application.persistentDataPath. it worked for me. it will looks like: File.WriteAllText(Application.persistentDataPath + "/saveFile.json", json);
Great tutorial! Is JSON + IO better than playerprefs in terms of performance? If I have to save settings, what's the best way? JSON or playerprefs? thanks.
You can use JSON in PlayerPrefs as well, its simply a string.Normally I store game settings with PlayerPrefs (Resolution, Keybindings, etc) and game state with save files.
Cheers!
5.42 : File.WriteAllText (Application.dataPath + "saveFile.json", json);
5.55 : File.WriteAllText (Application.dataPath + "/saveFile.json", json);
Good joke :)
After a few questions about this code that was not working, I was able to finish the video. Jason is a nice, accommodating little guy ...
I never know if dataPath ends with a slash or not, seems I always get it wrong heh
@@CodeMonkeyUnity Same on the September video: there are stealth slashes (and even SAVE_FOLDER).
In any case, I learned a lot of things (in particular to be wary of data coming from outside ^^).
Thanks, I hadn't really messed with the filesystem ...Great moment of solitude ...
One of your best videos
You're such a great teacher!!!
Thanks! I'm glad you found the videos useful!
This was a well made tutorial. Thank you
I just found thiss and it's some good info thank you I understand it a little better!
Awesome video, json files turn out to be great for storing item information
Clean and neat tutorial. Thanks and god bless you!!
Excellent tutorial, very helpful!!
Glad to hear it!
Thank you so much man.. I will achieve my game dev dreams thanks to people like you.
Go for it!
Awesome tutorial, I am new to this
Amazing tutorial.
Very clear explanation, great video ! :)
playerprefs much easy but i want to practice this concepts for cache purposes thanks
Thanks for quick and awesome tut easy to follow and awesome in practice!
I will use this for my twitch plays (game)
Cool. Quick and to the point. Thanks.
Thank you!..Awsome.. the best explanation ever
How would you securely save data using json? Should you encrypt the string and if so where would you store the key in order for it to be decrypted on load again? Great video btw!
strings are just bytes so you can encrypt them with any algorithm you want.
But if you're making a game, don't bother with trying to encrypt the saves, it's not worth the effort. If it's a multiplayer game, then store everything in the servers.
@@CodeMonkeyUnity Ah yeah alright, I guess you're right. Thanks for the reply, I really like your videos!
Could you make a tutorial on making a save/load system with multiple slots (Slot 1, 2, 3, etc)?
In XML or maybe Binary Formatter?
I have several videos coming up regarding a save system so stay tuned for those.
But just based on this video you can easily expand the PlayerData to add some fields for whatever you wish to store there.
For an Inventory System you could define your items with an enum and store it easily.
private enum Item {
Dagger,
HealthPotion,
}
private class PlayerData { public Item itemSlot1;
public Item itemSlot2;
}
thank you very much, for this great tutorial
3: questions Do you plan to delve deeper into this? What about serializers like odin? When is better to use sqlite?
I'm working on a couple of videos making a Save System, JSON will be used as a simple way to serialize a SaveObject.
I've not used other serializers, I either use JSON or bytes.
In a more advanced Save System I'm going to cover how to directly save bytes into a save file and embed a screenshot.
Cheers!
Thank you so much for this one!!! :)
This is an example taken by wikipedia. How can you access the postalCode field, and the type of phoneNumber?
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
],
"gender": {
"type": "male"
}
}
Its all about creating objects that match that pattern.
So in that case it would be this
public class SaveObject {
public Address address;
public class Address {
public int postalCode;
}
}
Then you would access saveObject.address.postalCode;
Thank you
Is it possible to save data to a JSON file and copy then paste the JSON file to another device that has the same project (in a build) to open the JSON file up there (in the build) and have all the data?
I’m making a level maker for my game and would like a way of copying the JSON file so others can open it up in the build.
Yup, JSON is just a text file so you can easily copy that around to anywhere you want.
Code Monkey at around 5:43 you said about seeing if saveFile.json will show up after putting in that code.I tried what you did and that file didn't show up. I'm perplexed by this because to my knowledge changes to the actual project data only appear during runtime or in the actual build of the project and those changes are reversed after the project has stopped running in Unity.
Seeing the text added to the json file outside of running the project does remind me of an old idea I had. So, If anyone else is confused about this; I created a saveFile.json in my project folder outside of unity and set an absolute path to that file because mine isn't in the base Asset folder and now it works.
This video is a good start to learning how to use json and I did learn from this.
The runtime memory data does get wiped as soon as the game shuts down (data stored in variables) but an external file is not automatically deleted.
Maybe you have some permissions issues. Add a Debug.Log to see where you're saving the file and what response the WriteAllText(); gets.
@Bebe Agachevo If File.WriteAllText(); doesn't throw an exception then it successfully made the file. So if you don't see any errors then chances are you're not setting the path correctly so it's being saved elsewhere. Try a simple path
string path = @"c:\MyTest.txt";
i fixed it by changing using persistentDataPath. i will looks like: File.WriteAllText(Application.persistentDataPath + "/saveFile.json", json);
Nice video! Thanks for showing how to use JsonUtility inside C#.I know that it's possible to use the Json file to "send" the data to some DataBase like SQLite or MongoDb. But how could we lock or cryptograph the data inside Json, so clever and curious player's like us couldn't get inside it, giving ourselves infinity Health, Bullets, God mode, all cards available, etc... ?
In a singleplayer game you really shouldnt waste time trying to stop cheating, better spend your time making the game better
In a multiplayer game you should never trust the player for anything so that would require a different design
Helpful tutorial :)
Hi, Awesome tutorial about JSON Thanks ! i would know if it's possible to save also gameobject ?
No, you can only store anything that can be converted into text so a reference in memory cannot be stored directly. You can store the type of game object (like if it's a type of weapon or something) or the object position and use that on loading. I handle saving and loading here th-cam.com/video/6uMFEM-napE/w-d-xo.html
Can you do an item database tutorial? Idk if I should stick with JSON, Regular Script initialization or serialized Scriptable Objects. I need some insight... Ive tried both and Im still unsure which way is better
can you make a quick tutorial showing how to make the basic character controller from the tf2 demoman, including the animations
It's tough because I'm using my custom animation system.
I did do some videos on the base of that animation system, check out the videos on how to create and modify a mesh through code, that's the core of the whole system.
Cheers!
TY, Good tutorial.
Awesome as always!!!
Cheers!
I'm trying to do this with bolt, what would be the visual scripting equivalent of creating a playerdata class for a json utility node?
I don't think there's any way to create a new class structure just with Bolt. But you can make a very basic C# file just to define the structure and then use it with Bolt
can u create a video on how to create json array
Is possible to do this without creating a class to store the values??, like just having an array of int and pass directly the data of the json
JSON stores key-value pairs so it needs a field to know the name of it. So yes you need a class/struct to hold the data, I don't think JsonUtility.ToJson(); works, although I never tried that myself
@@CodeMonkeyUnity confirmed that not works, i hace tried un that way but ir doesn't understand the strings so give an insanely big value(something like 1211111000).Thanks for the answer!!, just to mention contrats for tour c# course on teachable, i already finished it is really complete
I liked how you went into detail on how to do it, but I would like some help understanding how it does what it does, I'm just starting to make a practice app, and my friends wanted to make a dating sim. So naturally I have to learn how to make a save and load file system. I just need a little more help. Please and thank you.
JSON is a file format, what it does is really just type conversion from whatever type into string and back again.
Tehcnically the JsonUtility uses Reflection to find the class member fields and uses System.Convert to do all conversions.
I was trying to figure out how to find parse nested object doing it in reverse (ToJson) help me figure out how it should be formatted. Thanks A Mill
I'm having trouble with arrays within the JSON object. I've found that JSONUtility isn't so good with handling that, still trying to make this wrapper solution I've found on the forum to work but no luck. Wondering if you have had similar problems with array within a json object
What trouble? It works perfectly fine with arrays, just has issues with List and Dictionary
this video helps me a lot , thank u
thx!
I'm not all that familiar with JSON, however I noticed when it's saved in a file it's all on one line, is there a way to format it so it takes up multiple lines and is more human readable?
If you load that file onto a browser it will be parsed and it will be easy to edit.
I don't think Unity's JsonUtility has a PrettyPrint function
JSON is easy to make save and loading, but it's really easy to read which also makes it easy to modify, so a more better way of doing this is binary. Because their binary thier really hard to read which also make them very hard to modify.
Thanks for u! And for that comment too
Hey, i know this is a fairly old video, i wonder if you have any newer ones... I wonder if you could answer a question for me... How does one go about assigning a super complex JSON to an object without making a bunch of classes? For example, I have one I'm working on with a client, and the JSON being downloaded via an API get request he has me working with is like...
"data": {
"mainMenuConfig": {
"booksConfig": {
"content": [
{
"title": "",
"category_items": [
So, the only way I can figure out how to assign this is make an object for data, for mainMenuConfig, for booksConfig, for content, and for category_items, so 5 objects in total(most pointlessly holding another object lol, even the "title" variable isn't being used)?! I wonder, what is the point of these nested objects? lol, why does mainMenuConfig not just contain the "content"? But, that's besides the point, would you happen to know an easier way to assign these values without making a bunch of objects? FYI i need the Data because it actually contains another object further down(i just didnt want to make this comment gigantic lol).
But it took me like 2 hours to get all the values assigning... i wonder if there's a more efficient way to do this? Besides creating 5 useless classes to hold all this info lol, this isn't the first time I've come across overly complex JSON files containing seemingly empty, useless objects that just hold another object lol. I tried using JsonNode as well, but that just makes it so you have to assign each value manually and it makes the script look kinda sloppy...
Visual Studio has an option for "Edit > Paste Special > Paste JSON as Classes" which automatically creates the classes for you
Alternatively you can look into the dynamic C# keyword, although I haven't used it myself docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic
Questions about the structure of the JSON really should be asked whoever made that JSON, only that person knows, maybe they have a good reason for those empty containers, or maybe it's just bad code.
@@CodeMonkeyUnity Ohh, I didn't know of that paste JSON as Classes option. I once did a job for a client where i was just making like 10+ different classes out of JSONs, I was just pasting them one by one, erasing the values and turning them into variables, it took forever, that would've saved me a ton of time haha
Thanks for the help! I'll read that doc too to see if i can use that.
Very good tutorial, thank you. I saw your reply on a comment below saying that you wouldn't consider JSON as a "safe" way to store data. It is very easy to crack/access it for android apps for instance (i.e. quick editing it to hack the game). I know you wouldn't store anything really worthy on it but I'm just wondering if there's a better/safer way to keep players from cheating/bugging and keep things a little less exposed. I can't see how json would be better than making a proper encoded save system and using the cloud/database system on the platform you are using (firebase/steamcloud/google services/etc). Thank you!
The only way is to keep your secure data on a server and only give the player limited read access. If the player is in possession of the data then you should assume they can manipulate it.
But for the most part I would say don't bother with people cheating in your games unless you're making something multiplayer.
Performance wise, would it be good to use json to save every 10 minutes or so with a bunch of info like in a city builder?
And can i save/load json with Jobs if performance is an issue?
Sure a autosave every 10 minutes should work just fine, worst case scenario is your game hangs for a second but if its only once every 10 minutes it's unlikely anyone will be bothered by it.
I wouldn't bother jobifying the save code, it's not an issue unless for some reason you needed to save every second.
Thanks for the answer. Think I'll use json and playerprefs now
don't like necro threading but i tried using this and the file is not creating. i have a debug that shows string json is set to the data i expect but file.writealltext isn't writing to the file. This vid is 5 years old but did they change anything about how this needs to work since then or am i just missing something?
*edit*
Found the issue reading a different comment. There was a missing \ before saveFile.json but it was there after coming back from saving the file. works now!
heh yeah this has happened to me several times, always add a Debug.Log to verify you are saving exactly where you think you are to make sure you're not forgetting a /
despite making the PlayerData class when I save PlayerData playerData = new PlayerData(); it sais playerData does not exist in the current context.
It's like; I know that's why I'm making it :S
Before this, is it wise to create that variable in Start along with the save and load code? Shouldn't they be their own functions that you can call in your game?
Sounds like you instead wrote new playerData(); and the type is named PlayerData not playerData, remember that everything is case sensitive.
As to when you do that, yes in a proper game you would hook the load logic to some kind of UI button click and not on Start unitycodemonkey.com/video.php?v=6uMFEM-napE
@@CodeMonkeyUnity Thank you for your help :D Yes, will definitely save that one for monday. Cheers :D have a good weekend
But does this method support nested object as well?
Yes, as long as those types are Serializable
What if someone forging our json file manually and accidently delete some string & value. It could give some kind of error in the game, isn't ? Do we need some try-catch in our code or something or maybe set default value in that private classes ?
Yes JSON is easily editable so you need to validate your data
@@CodeMonkeyUnity Oke, Thank you sir !
What would be the process for saving for example a list of custom classes, that each contain list with additional custom class? What happens for me is, it only creates json with reference ID, which I actually don't need. I need the data from the classes in those lists, but I'm unable to get/save them.
You need to either use Structs instead of Classes, or manage references yourself with some kind of unique id system
How do you save the json data to an online storage using the "www" class?
That depends on whatever you have running on the server. That class is just for doing a HTTP request unitycodemonkey.com/video.php?v=Gk0-amfn5DM
What you do on the server depends on what you have in the server, could be a simple PHP script recording the incoming input onto a database
How do you get this to work with webgl
working with enum and list dont seem to work, I did convert on my enum into int, just doesn't work as expected
That is working as expected, enums are really int's with fancy names, so the serializer is doing exactly as intended. If you convert it back you will see the enum value again.
Lists also work, perhaps you're trying to save a list with a custom data type? If so you need to make sure that custom data type has the attribute [Serializable]
How do I make a list of playerdatas serializable? It always says there isn't anything in the list when I run it
You need to add the attribute System.Serializable to your custom classes th-cam.com/video/6uMFEM-napE/w-d-xo.html
why it's so easy?? Thanks
For days I have been trying to do such a simple thing as to write in the form of text on the screen the content loaded from the text file. All that works for me is writing this text to the console via debug.
YT tutorials do not work because they do not take into account Text Mesh Pro.
When I try to get help on websites for unity users, discord or forum, I only get "advices" to check my code thoroughly and fix it myself. I really have no more strength.
TextMesh and TextMeshPro works pretty much exactly the same, you just set the "text" field with the text you want, that's it. For reading the file you just use File.ReadAllText();
@@CodeMonkeyUnity no its not the same, you need to use using TMPro; and use TextMeshProUGUI thing, but when i try its breaking a script i dont know how to make it work, maybe by change text from the file to string variable and use this variable in visual script to change meshpro text but i try this for days and cant do it.
Если присмотреться, то этот способ очень хорош для сохранения больших объектов, не разбивая на составляющие, как я это делал используя PP. Урок мне понравился..
Is there a way to duplicate the json files? I want to create a json file everytime I start the game. This only updates de json file if it changes. How do I do that?
It's just a normal file, so you can just do File.Copy();
please make tutorial on built in json parsing specific response key
What do you mean parsing speecific response key? You mean contacting an API? That's going to depend on what API you are dealing with.
Usually you don't have to manually parse anything, as long as the field name and type match.
@@CodeMonkeyUnity yes that tutorial. Without using their party library. Most tutorials are only about saving and loading file. Need Jason rest API receiving method
How to work with array? like int [*, *, *]?
can u do it from another Endpoint server json
How to Parse the JSON to get an array of image URLs.? So that I would be able to assign those images to their respective UI Image Elements.
Not sure what you mean, a image URL is just a string so just create an object with a string value and parse the json onto it.
@@CodeMonkeyUnity Thank You for your response. I have parsed the JSON and stored the string URLs value into 3 different string variables Link1, Link2, and Link3. After that, when I am Passing those string values using start coroutine as its actual parameters (for example : StartCoroutine(DownloadImage(Link1,Link2,Link3)); to download images using WWW then It is giving me an error message " *uriformatexception: uri scheme must start with a letter and must consist of one of alphabet, digits, '+', '-' or '.' character* ". I probed Unity Answers and Asked question about my problem but didn't get response from anyone. I wonder why it is giving me this error even though the string contains valid URL starting with *https* ://.
I apologize for this lengthy reply but I want to get rid of aforementioned problem.
Great tutorial =D
legendary
Is it possible to create objects using json in unity?
What objets? JSON is just data, it can represent whatever you want
@@CodeMonkeyUnity Suppose, I have a json file like this,
[
{object 1 : [91,23,65]},
{object 2 : [44,23,85]},
{object 3 : [27,63,55]},
{object 4 : [25,33,25]},
{object 5 : [52,93,65]},
]
>>
So I was asking that can I create objects with given x,y,z co-ordinate using that JSON file?
@@tareqmahmud3902 You can create objects with the saved data, if you use them, but JSON cannot create objects on itself. It's just a method to save data like string, boolean, integer and anything you can convert into a text.
@@Inarilein yes, exactly what I was looking for! But how?
my json file has spaces so how do I put that in my program
if i turn off the computer can i load my last save?
You need to save data to something persistent th-cam.com/video/6uMFEM-napE/w-d-xo.html
@@CodeMonkeyUnity thank you!
What's a Vector
It's a Vector, something with X, Y and maybe Z en.wikipedia.org/wiki/Vector_(mathematics_and_physics)
If I want to save a static variable in json file, how can I do ?
Copy it into whatever object you're converting into json, check out these videos th-cam.com/play/PLzDRvYVwl53vRrMuPBkNNZUmnl1jCHcHs.html
Just add a field in the SaveObject
WOW thank you so much
Nicey nice!
Wait, isnt it super easy to hack json data if it is so easy to read?
Yes JSON is intended to be easy to read and write so it's not suitable if you're concerned about security.
But unless your game is online or extremely specific I wouldn't worry about people hacking their own single player save games.
Use Binary Serialization instead, a secure way for saving and loading data.
What if my class has a Sprite inside? I can't serialize it)
You need to reference it in some way, maybe store the sprite's name, maybe a GUID. Alternatively you can serialize an image with base64, I actually covered how to include a screenshot in your save file here unitycodemonkey.com/video.php?v=dqySkMFieHE
It works on android o IOS?
Yes you can use JsonUtility while building for mobile.
Lol who is jason and why is he in my computer
i mean the data can be easily manipulated by anyone who knows how to work with JSON?
JSON is not meant for security, it's not encryption, just a nice data format that is easy to handle and recognized in so many languages/APIs
@@CodeMonkeyUnity ohh thanks for the information!
❤🧡💛💚💙💜
I have a better one. Who is json ?
JESUS CHRIST!!! HOW DA FCKING USE THIS FILE!!!! I HAVE .JSON....AND I DONT KNOW HOW USE IT!!! WHY YOU DONT TELL THIS???
XML is better!
Well it depends on what you're doing but JSON is much cleaner and much more supported pretty much everywhere.
I wouldn't recommend XML unless you absolutely have to.
Thank you so much for this amazing tutorial