SAVE & LOAD SYSTEM in Unity

  Рет қаралды 1,137,528

Brackeys

Brackeys

Күн бұрын

Here's everything you need to know about saving game data in Unity!
► Go to expressvpn.com/brackeys , to take back your Internet
privacy TODAY and find out how you can get 3 months free.
● Easy Save: bit.ly/2BzgdXb
❤️ Donate: www.paypal.com/donate/?hosted...
····················································································
♥ Subscribe: bit.ly/1kMekJV
● Website: brackeys.com/
● Facebook: / brackeys
● Twitter: / brackeystweet
● Instagram: / brackeysteam
········································­­·······································­·­····
► All content by Brackeys is 100% free. We believe that education should be available for everyone.
❤️ Donate: www.paypal.com/donate/?hosted...
········································­­·······································­·­····
♪ "ES_Dress Code_Black - oomiee" by Epidemic Sound

Пікірлер: 1 800
@lilmonster5684
@lilmonster5684 5 жыл бұрын
"So you've made a game and it played nicely.." Me: umm
@OutOfNameIdeas2
@OutOfNameIdeas2 5 жыл бұрын
*Syntax error on line 142* Me: *Code ends at line 78* ?!?!?!
@QuietSnake-xs5vx
@QuietSnake-xs5vx 4 жыл бұрын
@@OutOfNameIdeas2 xD
@emeralaxy850
@emeralaxy850 4 жыл бұрын
VR Ready Pc Fan Me: creates script with 100 lines C#: You have 736 errors and I won’t tell you why
@JW-oe6nw
@JW-oe6nw 4 жыл бұрын
​@@emeralaxy850​ *one missing semicolon*
@minecraftermad
@minecraftermad 4 жыл бұрын
@@JW-oe6nw 2 missing brackets
@thepokednoob9497
@thepokednoob9497 3 жыл бұрын
Brackeys: "And now, we are ready to try it out" Me with 5 errors: *"yes"*
@harshvardhanmisal2255
@harshvardhanmisal2255 3 жыл бұрын
@TRAGE GAMING he probably missed a lot of simple and basic stuff
@subzero4787
@subzero4787 3 жыл бұрын
me 1 error
@harshvardhanmisal2255
@harshvardhanmisal2255 3 жыл бұрын
@Anant Tiwari a lot of times we have to change code to meet our needs
@animationspace8550
@animationspace8550 3 жыл бұрын
@Anant Tiwari it's clear by the amount of bad spelling they are either joking, or really bad at spelling
@fahimjunayed5894
@fahimjunayed5894 3 жыл бұрын
You're lucky, but I am now with 13 errors.
@shahryar50
@shahryar50 3 жыл бұрын
I feel a little sad watching the videos now knowing they stopped
@sh0unakgg274
@sh0unakgg274 3 жыл бұрын
Yeah
@payaldasgupta394
@payaldasgupta394 3 жыл бұрын
Yeah
@pythonhtmljava7811
@pythonhtmljava7811 3 жыл бұрын
İndeed :(
@goodgamershow6505
@goodgamershow6505 3 жыл бұрын
Yeah
@goblinslayer6375
@goblinslayer6375 3 жыл бұрын
He is not death yet. He just doesn't want to upload more. He still reading your comment.
@bonestudios7777
@bonestudios7777 5 ай бұрын
5 years in and still this is one of the best save and load system tutorial that I found out there.
@Chubzdoomer
@Chubzdoomer Ай бұрын
It pains me to see that so many people have upvoted this comment. BinaryFormatter is notoriously bad and even Microsoft themselves warn NOT to use it due to its security issues. JSON is the way to go today, and really has been for years.
@imtiazsabree6562
@imtiazsabree6562 Ай бұрын
thanks for the comment. I am about to start and needed to know if it still fits.
@Chubzdoomer
@Chubzdoomer Ай бұрын
@@imtiazsabree6562 It doesn't. DO NOT use BinaryFormatter. Microsoft themselves advise against it.
@sykoo
@sykoo 5 жыл бұрын
Oooo great one! I think this is one of the features *all* games need, but almost *no one* knows how to do it lol. Well done man! ⭐
@squarewarriorgames3737
@squarewarriorgames3737 5 жыл бұрын
What about the LD game with u and noa :D
@anubhavgupta3562
@anubhavgupta3562 5 жыл бұрын
I had given the suggestion of this on your channel also
@nein3405
@nein3405 5 жыл бұрын
if with almost no one, you mean non professionals who download unity and think they can make the next big instance of whatever genre is most popular atm in just a few clicks, then yes, otherwise no. i mean there is nothing bad about it, everyone needs to learn at some point, but if you fail with this, you are so deep in the learning phase, you wont create distributatble games the next couple of years.
@SlayPlenty
@SlayPlenty 4 жыл бұрын
Wheres the rpg tutorial
@redbepis4600
@redbepis4600 4 жыл бұрын
yeah! I made clicker game but everything whould just reset
@Zicore47
@Zicore47 3 жыл бұрын
Quick code review ;-) * Use using statements for classes that implement IDisposable (e.g. FileStream, BinaryFormatter etc.). Like previous commenters said. * Use System.IO.Path.Combine to combine paths safely. Paths are constructed differently on different OS. This avoids a lot of potential problems. * Use a helper method to convert from Vector3 to float array or better yet, make own struct that contains 3 variables and convert between these.
@LukeAps
@LukeAps 2 жыл бұрын
Thanks man. Yeah, tutorials like this need review. Combine is a crucial thing to point out for OS compatibility.
@xXrandomryzeXx
@xXrandomryzeXx 4 жыл бұрын
I really wish that every unity tutorial was by you, like you explain so well and it's so fun learning by you.
@Zukomazi
@Zukomazi 5 жыл бұрын
Love it had to watch 3 different tutorials, Everyone else missed some steps, or didn't fully explain everything and i couldn't get it working. Watched this and now i can save my Gold x, Potions x a, and Apples as well as the position. Works great. Now i need to fully understand, Don't destroy on load. Thanks a lot!!
@speedyzolt
@speedyzolt 5 жыл бұрын
You’re amazing. As an artist I find your tutorials easy to follow. Thank you and your team of people. KZbins best Unity programming specialist. I’m inspired please continue this channel.
@CouchFerretmakesGames
@CouchFerretmakesGames 5 жыл бұрын
It was simple enough, but also in-depth as well! Thanks!
@kodo777
@kodo777 5 жыл бұрын
again, seeing you in places I didn't expect
@CouchFerretmakesGames
@CouchFerretmakesGames 5 жыл бұрын
@@kodo777 I'm everywhere!! #EvilLaugh
@SafaAlkan
@SafaAlkan 4 жыл бұрын
*Does this script allow the player to resume on which stage he / she stayed in later?* Do you know?
@alexanderfrye2688
@alexanderfrye2688 4 жыл бұрын
@@SafaAlkan I'm not sure if you still need to know, but yes. You'd simply need to store the current stage as variable such as an int and use it just like you would any of the variables the video shows.
@raydartt
@raydartt 3 жыл бұрын
Thanks man! I have watched this tutorial several times always afraid to tackle this. But now that my game has developed to the point that I need this I had to tackle it. What a surprise how easy it was. I started by making checkpoint for when my player dies and it takes me right back to the latest checkpoint. I learned a lot.
@Gapthrosnir
@Gapthrosnir 4 жыл бұрын
This is perfect timing! I was about to start working on a save system over the weekend.
@AlanDarkworld
@AlanDarkworld 5 жыл бұрын
Please, for the love of god, when you are working with a FileStream, please use a try-finally block and call "close()" in the finally clause. Otherwise, if your deserialize() fails, the file will remain open, which can lead to some super-weird and hard to debug effects.
@chkypros
@chkypros 5 жыл бұрын
Actually, since FileStream implements IDisposable, you could use the using statement which would effectively do the same but is cleaner. docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
@AlanDarkworld
@AlanDarkworld 5 жыл бұрын
@@chkypros Good point, but let's not forget that this is for beginners... I'd be more than happy if they manage to use try-catch for a start.
@Ziplock9000
@Ziplock9000 5 жыл бұрын
@@AlanDarkworld Using is more beginner friendly
@s-.-8821
@s-.-8821 5 жыл бұрын
I am getting fucked cause of that
@DynaZor
@DynaZor 5 жыл бұрын
Can you please give an example? I don't know how to do that...
@texturem0nkey
@texturem0nkey 4 жыл бұрын
This is a great tutorial. I found it much more useful to use lists rather than arrays for breaking up the Vector3's, however. When you save out, you can break the V3 into separate floats, and then reassemble them on load. This has been particularly helpful for me in trying to save/load multiple groups of item data in a single file, as opposed to just a single item as would be possible with the former method. Also to note it's relatively easy to go from where he has started, to a system where you can specify save/load filenames, and read out items from a directory. If anyone is interested, I can post the code for all of that.
@hjc1710
@hjc1710 4 жыл бұрын
Nice tutorial as always, really appreciate you linking to assets and the humor and fun you bring to your vids!
@IsaacPrice
@IsaacPrice 2 жыл бұрын
I'm building my first game using Unity and this is exactly the simple save system my game can make use of, since it's not going to be huge. Love these concise videos!
@DukaSoft
@DukaSoft 5 жыл бұрын
Thanks for not just going: "Hey guys, this thing from the app store will do it all for ya.. Bai o/ " This tutorial was actually helpfull!
@TinJ7
@TinJ7 4 жыл бұрын
hahaha good point
@creationsmaxo
@creationsmaxo Жыл бұрын
One important thing that is missing in this tutorial is to actually separate the data (PlayerData in this instance) from its FileStream cached data. In this video, it would be a function like: public PlayerData CopyPlayerData(PlayerData From){ PlayerData To = new PlayerData(); To.level = From.level; To.health = From.health; To.position = new float[3]; To.position = From.position[0]; To.position = From.position[1]; To.position = From.position[2]; return To; } The reason for doing this is to separate the data sent to the game-usable data from the Filestream data. Remember that you cannot generate an hard copy a Serializable class (PlayerData in this case) using = . An hard copy of a Serializable class is a copy cached as its own. It can only be done by using "new". So, when you do something like SerializableClass A = SerializableClass B, you're basically add a link reference from A to B. A becomes dependent of B meaning that if B cease to exist, A becomes Null and if B becomes Read-Only, A cannot be edited anymore. This is unlike something like float A = float B which makes A equal to B. Unity, and pretty much any game engine, are NOT able to generate an hard copy a Serializable Class because it ignores what's to copy. The only way to generate an hard copy (cached) of a Serializable class is to cast it as a new one. As such, SerializableClass A = new SerializableClass(); makes sure that A is an instance of a Serializable class of its own. When doing so, the class is obviously in its Default state, hence it's at that point that you want to copy its individual values (and by copying, I mean making its values equals and not just some soft copies).
@TidaliCreative
@TidaliCreative 2 ай бұрын
Is this still the case?
@ayushigarg13
@ayushigarg13 4 жыл бұрын
Your tutorials are amazing! Descriptive and clean, really suitable for beginners like us. Thanks a lot :)
@martinlarra1530
@martinlarra1530 9 ай бұрын
ur mom
@BrianLindahl
@BrianLindahl 2 жыл бұрын
Excellent video and description of the process. Exactly what I was needing. Keep up the great work!
@CoolJosh3k
@CoolJosh3k 5 жыл бұрын
12:10 If you have it set to automatically load data, this will log an error the first time the game is played. You could of course have a load option and disable that if the save file is not found.
@mangiux94
@mangiux94 4 жыл бұрын
15:00 add if(data != null) { // Attributing the variables }
@IronDizaster
@IronDizaster 5 жыл бұрын
Could you maybe in the future make a tutorial on the " Easy Save " plugin you mentioned later in the video?
@kellyrodgers9326
@kellyrodgers9326 3 жыл бұрын
Brackeys guy, your tutorials are amazing. You make things so easy to understand. Thanks sooo much for all your great tutes.
@AxZelAnimations30
@AxZelAnimations30 2 жыл бұрын
I remember doing this a year ago and attempted to implement it without understanding so much that it broke my game. Not exactly but I had to remove alot. It was working but I did something in the script after doing some of my own additions. Now I'm here again with a little bit more of knowledge.
@scriptbrix
@scriptbrix 5 жыл бұрын
Quick tip: Look up how to use the using() statement in C# when working with unmanaged resources such as files. The good news with using the "using" statement is that the file stream will be guaranteed to be closed if you forget to do so yourself.
@Unknown-bm5ui
@Unknown-bm5ui Жыл бұрын
You are the godfather of programming for me. Thank you so much for everything you do.
@kepygames
@kepygames Жыл бұрын
Did
@TheOneAndOnlyCode
@TheOneAndOnlyCode Жыл бұрын
exactly
@notcade917
@notcade917 Жыл бұрын
brackeys is father
@Gitko01
@Gitko01 5 жыл бұрын
THANK YOU FOR UPLOADING THIS VIDEO! I HAVE BEEN LOOKING FOR THIS FOREVER!
@nullified__
@nullified__ 5 жыл бұрын
I Like The Way That Brackeys Moves When He's Instructing Stuffs!
@romanglinnik8073
@romanglinnik8073 5 жыл бұрын
That momet, when you've recently finished your Saving script and a tutoriel about saving/loading by Asbjorn shows up👍
@toddchavez5374
@toddchavez5374 5 жыл бұрын
Yeeee that was I needed! *thank you Brackeys*
@Laiser
@Laiser 4 жыл бұрын
Weebs everywhere
@Dj-ck6co
@Dj-ck6co 4 жыл бұрын
I really enjoy watching your videos you always explain everything
@nostalgic8945
@nostalgic8945 3 жыл бұрын
Always coming back to this tutorial, we will miss you king! ❤
@cgcowboy
@cgcowboy 5 жыл бұрын
Thank you! Perfect timing! I would really love to see how to extend this capability to AWS for cloud saving as well.
@ebanwolf6288
@ebanwolf6288 4 жыл бұрын
Hey man ur Awesome, Im ending a work of my carreer and it videos help me a lot. Congrats from Spain !
@michaeldurocher5035
@michaeldurocher5035 4 жыл бұрын
Very nice video. Extremely helpful without any unnecessary additions that might potentially confuse. Thank you.
@AKSenor24
@AKSenor24 4 жыл бұрын
I am very excited! Super tutorial, now it's working with my invector shooter template. You are really awesome!
@tartaro-mk6hv
@tartaro-mk6hv 5 жыл бұрын
Love your tutorials!! Can you make a guide on in-game purchases through unity??
@sharpiebandit6740
@sharpiebandit6740 3 жыл бұрын
I also need this
@newtongamer5574
@newtongamer5574 5 жыл бұрын
Wow! Last night I was thinking about how to make a save system for my game ... And suddenly I see a notification: Brackeys - Saved System in Unity and I stayed: thank God :D
@galaxy4dayz
@galaxy4dayz 5 жыл бұрын
xd
@botcomborderreaching3518
@botcomborderreaching3518 2 ай бұрын
Huge shout out, Im glad that you are explaining every single line of code, it really helped me.
@StellarMirage
@StellarMirage 2 жыл бұрын
Finally, after watching it for the 20th time I understood the flow after doing a dry run!! I wish Brackeys returns!!
@ArjolP
@ArjolP 4 жыл бұрын
Thank you Brackeys. I just finished my freshman year as a Computer-Engineer student. I really love programming and I am making little games (alongside from other projects) in my free time in hopes of improving my abilities. I am not extremely knowledgeable at the moment so your videos are extremely helpful. It is quite interesting to me how what I learned in University about File Handling, albeit in C and not in C#, turned out to be quite useful here. I thought Unity would use a completely different way to handle the game files. It was a nice surprise to see they are not doing that (apart from a couple of different things like _persistentDataPath). It feels really nice to know that what I am learning in University can actually be applied in what I do. I know, it is silly for me to say that, because that's what Universities are for, but sometimes it feels like I am just wasting my time there, being taught things that I will never use in everyday life.
@alejandroh.ontoria6457
@alejandroh.ontoria6457 6 ай бұрын
Hey, did you end up working in Game dev?
@colbysnodgrass3997
@colbysnodgrass3997 5 жыл бұрын
This is neat and definitely one of the more understandable binary save systems out there so great job on that, loved the video. I do have one question, how would you go about extending this to say an inventory? While brainstorming, I thought you might be able to have a library of items to reference and store say an integer value as an id for each item to access it, however with large games like Skyrim I feel this could become tedious.
@PenguiLino
@PenguiLino 6 ай бұрын
Yeah im four years late to this but for anyone with the same question now So i first defined a simple class with an id and how many you have: public class InventoryItem { public int itemID; public int Amount; } Then i make a dictionary of all the items and their corresponding Id's foreach(Item item in Items) { Items.Add(item.ItemID, item); } Then when im loading the items i can use this foreach (InventoryItem item in data.inventory) { AddItemToInventory(Items[item.itemID], item.Amount); } And in order to save the items i can do the opposite and get Ids from items In the data script I just have a list of InventoryItems: public List inventory; and just update that with the encrypted items.
@spitfyre7165
@spitfyre7165 4 жыл бұрын
Thanks so much! Awesome tutorial! I spent ages trying to do this and it was so satisfying when it finally worked in my game. Thx so much!!!!!!!
@kapkoder4009
@kapkoder4009 4 жыл бұрын
Thank you so much for this awesome HIGH QUALITY simple tutorial 😝 your voice is soothing lol
@seb4542
@seb4542 3 жыл бұрын
Funny Fact: You can adapt Vector3 and even your own scripts for the formatter to save them to binary, it's a little bit longer, but its really useful when you need to save multiple objects and their positions
@Black_Raven-
@Black_Raven- 3 жыл бұрын
How i can did it?
@xipheonj
@xipheonj 4 жыл бұрын
In your save chain you have the SaveSystem handling the data, it's simply passed the player. In the load chain you pass the data itself back to the Player class and let that class handle the data object. You need to pick a convention. Either pass the player to the SaveSystem.LoadPlayer function as well and have that class manage the data, or pass the already formatted PlayerData object to the SaveSystem.SavePlayer function instead of the player.
@cankarkadev9281
@cankarkadev9281 5 жыл бұрын
This was a very simple understandable and helpful tutorial! Thank you very much! :-)
@ukaszwach6416
@ukaszwach6416 5 жыл бұрын
This is exactly it, what i looking for. Thank u man :D
@ramizian
@ramizian 5 жыл бұрын
Man, your tutorials are really awesome! - You know exactly what you're doing - Your tutorials are pretty clear as a newbie/pro - It's not too long to watch - I'm actually learning something It's so rare nowadays to find KZbinrs like you, who are able to teach us effectively things in Unity. Love the work you've done
@SlayPlenty
@SlayPlenty 4 жыл бұрын
Cough cough sykoo
@h4z4rd1000
@h4z4rd1000 5 жыл бұрын
You should use the "using() {}"-statement when working with classes implementing IDisposable. using(FileStream stream = new FileStream(path, FileMode.Open)) { // Do Something with the file } This way the file handle will be closed even if an exception is raised from the code inside the curly brackets. You don't need to call .Close() or .Dispose() yourself. Also writing a binary file might be more secure than a plain text file, but in the end, locally stored progress can always be changed, we can only make it more difficult.
@DynaZor
@DynaZor 5 жыл бұрын
For some reason it doesn't work for me... I put your lines instead of the Filestream line of Brackeys, put the PlayerData line between the brackets, then it says "Invalid initializer member declarator" on PlayerData and "Use of unassigned local var.." on stream..
@MartinReinoso
@MartinReinoso 5 жыл бұрын
@@DynaZor it is missing a bracket : using(FileStream stream = new FileStream(path, FileMode.Open)) { // Do Something with the file }
@mekolaos9341
@mekolaos9341 4 жыл бұрын
I was wondering if there was a "with" keyword in C# like in python. Thanks for the tip !
@SafaAlkan
@SafaAlkan 4 жыл бұрын
*Does this script allow the player to resume on which stage he / she stayed in later?* Do you know?
@zuweijin6237
@zuweijin6237 4 жыл бұрын
then where to put the "return data " line?
@PedroHenrique-ci8fy
@PedroHenrique-ci8fy 4 жыл бұрын
I always come to this video whenever I need to implement this on my games! I need to really understand what's going on so I can do it by myself next time, thing are still a little bit fuzzy in my head :(
@TbM
@TbM 4 жыл бұрын
Nice Video, small shortcut I always use: CTRL+D will duplicate the line your cursor is actually in OR the part you have selected, instead of doing COPY+PASTE all the time when you have to duplicate anything in your code...
@PTurtle
@PTurtle 3 жыл бұрын
Me - nowhere near completing my game Also me - *I think I should add a save function*
@joeman123964
@joeman123964 2 жыл бұрын
you should. i always make it as i add content. trust me after having over 100 variables and objects (levels bosses etc) you need to save everything!
@greyfireocelot6140
@greyfireocelot6140 2 жыл бұрын
Right there with you. I have very basic stuff in and limited HUD elements with no levels or graphics even and I'm like "Yep, need a Save system"
@stellarstudio5495
@stellarstudio5495 5 жыл бұрын
There is a way to save Unity specific types like vectors, sprites, audio clips, etc. As you know, this can be done with JSON, but not be secure. So instead save the class in JSON format and then convert it into binary data. That let's us save a larger variety of fields and is nearly just as fast. Also perhaps XOR the binary with a secret key since anyone can convert binary back into original data. Or if you want to be really secure, encrypt it with AES. Good tutorial, quick and to the point. 👍
@lostconflict9369
@lostconflict9369 5 жыл бұрын
That's actually a pretty cool idea, i tried looking into AES a while back, got a few scraps of info. Mind sharing sources of info? Videos or forums idm.
@sloankelly
@sloankelly 5 жыл бұрын
Lost Conflict I made a video using AES to encrypt save data Encrypt Save Games in Unity with AES kzbin.info/www/bejne/iYnEZ52JjJyWobs that might be of some help
@stellarstudio5495
@stellarstudio5495 5 жыл бұрын
@@veilzahkaay9419 unless it's server side, but that's a whole other story.
@diadetediotedio6918
@diadetediotedio6918 5 жыл бұрын
@@veilzahkaay9419 you can obfuscate code, and using ILCPP, the code turns native
@lostconflict9369
@lostconflict9369 5 жыл бұрын
@@sloankelly Oh ty really appreciate it.
@MiddleCross378
@MiddleCross378 4 жыл бұрын
I freaking love your face bro! It's always so pleasant with that smile like your subconsciously encouraging us in our individual projects. Thank you for your hard work with these vids and please don't ever change.
@Top10AINews
@Top10AINews 5 жыл бұрын
Great tutorial! It helped me a lot with my game. The only thing now is that I need a way to save the gameobjects that were instantiated and destroyed so when the player resumes the game after closing it, he gets the same scene state as before. I’m totally stumped on that.
@jessemauritz1
@jessemauritz1 4 жыл бұрын
This is a great tutorial! i just had one question, I am new to coding. I wanted to reset the player position when a new scene is loaded and can not seem to do it correctly. How would I go about that using this saving method?
@LaCreArthur
@LaCreArthur 5 жыл бұрын
"I'm gonna write fun, just to make this tutorial a bit more fun" lmao x'D. Thanks for the vids
@Jermz0r
@Jermz0r 5 жыл бұрын
Great tutorial ive been looking for this for quite some time!
@adamrushford
@adamrushford 3 жыл бұрын
Also I love how you're displaying the binary as hexidecimal and actually describing it as 0's and 1's but it's clearly a-f 0-9 alphanumeric
@jimdim2222
@jimdim2222 5 жыл бұрын
*takes newly made binary save file and converts it online to edit my save file* Brackeys: "Am I a joke to you?"
@kas-lw7xz
@kas-lw7xz 4 жыл бұрын
You wanna have security? RSA
@dennisgonzales9521
@dennisgonzales9521 4 жыл бұрын
If you're concerned about being reversed engineered then I suggest using encryption to your serialized data before saving, and then using decryption after de-serializing.
@xfata1err0rx89
@xfata1err0rx89 4 жыл бұрын
Easy enough to just manipulate the data once it's loaded into the RAM and then let the game save that data to your save file. Best security you're going to get with it is having it saved onto an external server so you can better control the data and how things are processed so their local end is synced with the server instead of the other way around. For many single player games, that's not really necessary unless you have systems that tie into an online system such as leaderboards/achievements.
@Zethneralith
@Zethneralith 5 жыл бұрын
It's a bit more manual, and you have to update the methods every time you add data that needs to be saved/loaded, but another method I like to use is a BinaryWriter: using UnityEngine; using System; using System.IO; public static class ClassThatSavesThings { public const string PLAYER_SAVE_PATH = @"C:\The\Path\To\The.file"; // The '@' automatically escapes backslashes. public static void SavePlayer(Player player) { // Using a "using" statement causes the stream to be closed automatically when exiting the using. This is important because nothing is really written to disk until the stream is closed. using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(PLAYER_SAVE_PATH))) { writer.Write(player.level); writer.Write(player.health); writer.Write(player.transform.position.x); writer.Write(player.transform.position.y); writer.Write(player.transform.position.z); } } public static void LoadPlayer(ref Player player) { using (BinaryReader reader = new BinaryReader(File.OpenRead(PLAYER_SAVE_PATH))) { player.level = reader.ReadInt32(); player.health = reader.ReadInt32(); player.transform = new Vector3( reader.ReadSingle(), // "Single" is just another name for "float" in this case. It's technically the other way around, but whatever. reader.ReadSingle(), reader.ReadSingle()); } } } Of course, this is a quick and slightly dirty way to do it, but it gives you tons of control over exactly how the data is formatted in binary. The main thing to watch out for is ensuring you read/write data in the same order, otherwise you'll get wrong values for sure. You can also use a BinaryWriter to write to a MemoryStream instead of a FileStream. This is great when you want to get the binary as an array of bytes (byte[]) which can be used to convert your data into Base64. I wrote this in a plain text editor, so there may be some invalid syntax.
@raveheart58
@raveheart58 4 жыл бұрын
You're an absolute legend Brackeys! Cheers!
@Charlesw_88
@Charlesw_88 4 жыл бұрын
Thanks for this Brackey. Your videos are always helpful .
@MaskedImposter
@MaskedImposter 5 жыл бұрын
This tutorial fills me with determination.
@daredeflon662
@daredeflon662 4 жыл бұрын
Your health has been fully restored.
@miaoumixed4268
@miaoumixed4268 4 жыл бұрын
Hi, thank you much for this tuto, I am at a point building my game where i need the player to save his progression. Unfortunally, the file is not saved... Trying to find why... (of course my scripts are identical to yours.) M. D.
@academia_eduard
@academia_eduard 4 жыл бұрын
Thanks, Man, it works. I load this data when I create a scene in a c# script in Start, and I Save It when I do an action that counts, like when I collect a gem in the world.
@gnomge
@gnomge 2 жыл бұрын
Watching this today so my brain can recreate this during the night, so I can simply forget everything and have to watch this again tomorrow when I'm actually recreating this
@christofflinde
@christofflinde 4 жыл бұрын
"So I've gone ahead and set up a simple example level" Me: uuhhmm
@katowo6521
@katowo6521 5 жыл бұрын
2:47 "binary" Shows hex
@krushnaa5
@krushnaa5 5 жыл бұрын
o O 0 What he said is still true - data is converted into binary. Hex is just a shorter form for displaying it. For example 'F' in Hex is '1111' in binary.
@krushnaa5
@krushnaa5 5 жыл бұрын
@@jonsnow1092 That's exactly what I meant - Hex was used in the video as a short form for displaying binary. Of course they are two different number systems - else it wouldn't look any different from each other.
@alvesvaren
@alvesvaren 5 жыл бұрын
Hexadecimal is a way of shortening binary, instead of showing like 1111000000010011 you just show F013
@alvesvaren
@alvesvaren 5 жыл бұрын
jon snow Yes, but because a byte is really a number between 0 and 255 you can represent them with 4 numbers in hexadecimal
@Amongalen
@Amongalen 5 жыл бұрын
And then if you think about it you realise that in fact both are stored as binary. And so are plain text files. Everything is stored in binary files.
@sorasiro6951
@sorasiro6951 5 жыл бұрын
thank's so much, perfectly explained, much love
@cardsatanywhere363
@cardsatanywhere363 Жыл бұрын
Why does learning stuff like this make me all giddy and excited?
@maythesciencebewithyou
@maythesciencebewithyou Жыл бұрын
You should not use this anymore though. Microsoft itself is warning people from using the BinaryFormatter. From their MSDN: "The BinaryFormatter type is dangerous and is not recommended for data processing. Applications should stop using BinaryFormatter as soon as possible, even if they believe the data they're processing to be trustworthy. BinaryFormatter is insecure and can't be made secure" This video should either be taken down or have a warning.
@saras2743
@saras2743 3 жыл бұрын
Make sure the function in PlayerData is the same name as the class and is NOT a public void, otherwise there will be an error in the SavePlayer function. I had to comb through my code to find that mistake xD
@hairyspider151
@hairyspider151 3 жыл бұрын
TYSM i had this exact problem and this fixed it
@OcnarfPro
@OcnarfPro 2 жыл бұрын
That is how you make a constructor
@BirdWithAFinger
@BirdWithAFinger 2 ай бұрын
When I did that it gave me an error in SavePlayer script
@saras2743
@saras2743 Ай бұрын
@@BirdWithAFinger is your SavePlayer a script or a function? make sure its in the SaveSystem class
@noormuhammad5923
@noormuhammad5923 3 жыл бұрын
is it me?, or does brackey sound more friendly than a Canadian
@V.Z.69
@V.Z.69 3 жыл бұрын
what is a brackey?
@saifee7899
@saifee7899 3 жыл бұрын
man im a canadian and all i have to say is *ive never met anyone nicer than brackeys* expect my dentist lol
@carlsonraywithers3368
@carlsonraywithers3368 3 жыл бұрын
@@V.Z.69 it's supposed to be a bracket
@doublepickaxeyt3400
@doublepickaxeyt3400 4 жыл бұрын
This actually worked. This is amazing! Thanks so much! 100/10 would recommend and watch again.
@saramotamaralayefaemmanuel9772
@saramotamaralayefaemmanuel9772 Жыл бұрын
sorry im having error they type or namespace name 'PlayerData' Could not be found (are you missing a using directive or assembly reference)
@idrawpictures9140
@idrawpictures9140 2 жыл бұрын
brackeys with the guardians of the galaxy soundtrack in the background while i develop a game about cats with machine guns. doesn't get much better than this
@uovo
@uovo 5 жыл бұрын
'wow its not the first time i struggle to do something in unity and a few days later the best Unity teacher (brackeys) does a video on how to do it!
@jonasw7629
@jonasw7629 3 жыл бұрын
10:34 If I enter player here (I use "allTimeScore" but that doesn't matter) I get the error message : The name "allTimeScore" is not available in the current context. I've been trying to find a solution for hours, I did everything the same way. I don't know what the reason is!
@GamesBySaul
@GamesBySaul 4 жыл бұрын
Thank you for this tutorial it works perfectly for my mobile game! :)
@kyjacobs3346
@kyjacobs3346 2 жыл бұрын
What makes me so happy about the way Brackeys used to teach us is the way if shoes us the flaw first and then shows us a better way to do it. Like at 9:25
@blokbustr
@blokbustr 5 жыл бұрын
I’ve seen Nintendo use that binary system a lot
@UltraHylia
@UltraHylia 5 жыл бұрын
This doesn't work for me, for some reason my script isn't creating the file. EDIT: I fixed the problem! Basically, you cannot store your files inside of a folder, it has be the persistentDataPath and then + filename, no folders.
@ratboyOwO
@ratboyOwO 4 жыл бұрын
I had to watch this through a couple of times but I understand it much better now. thanks for the great tutorial!
@ratboyOwO
@ratboyOwO 4 жыл бұрын
also is there a faster way to tell the constructor what variables to assign? I have about 40 and its pretty tedious to keep typing them all out one by one.
@muzainahaque8167
@muzainahaque8167 2 ай бұрын
@@ratboyOwO i know i am like 3 years late to this comment but did you ever found a solution? cuz i am making an rpg game so like there are alot of quests, enemies etc to save
@destroyer9241
@destroyer9241 Жыл бұрын
Great Tutorial! Had to redo everything because I got stuck but after that it worked perfectly.
@bckb604
@bckb604 4 жыл бұрын
How would you save and load if there are multiple instances of the same class that all inherit from MonoBehaviour ??
@bckb604
@bckb604 4 жыл бұрын
@Ethan Bettenga I'll try that out. Thanks!
@cmpmusic9389
@cmpmusic9389 3 жыл бұрын
Couldn't quite understand. Can you explain more. Just a little more detailed. Thanks
@cmpmusic9389
@cmpmusic9389 3 жыл бұрын
@Ethan Bettenga
@bckb604
@bckb604 3 жыл бұрын
@Ethan Bettenga I ended up using playerperfs, but I would love to see your solution for this!
@cmpmusic9389
@cmpmusic9389 3 жыл бұрын
So do I
@_Daus_
@_Daus_ 5 жыл бұрын
Can you make a tutorial how to input data to google spreadsheet in unity and use the data from the google spreadsheet in unity?
@MarioManTV
@MarioManTV 5 жыл бұрын
I would use this tutorial: www.red-gate.com/simple-talk/dotnet/c-programming/calling-restful-apis-unity3d/ And adapt it for use with the Google Sheets API here: developers.google.com/sheets/api/reference/rest/
@Diamond-yn4nu
@Diamond-yn4nu 4 жыл бұрын
thank you very much for this excellent tutorial , you always provide important functions at the heart of games development, keep going.
@bombshellgames2321
@bombshellgames2321 3 жыл бұрын
This improved my game 10x times! Thank you!
@badgamedevreacts3855
@badgamedevreacts3855 4 жыл бұрын
14:36, bruh i spent 5 min trying to figure out what was wrong with my code then i played the video for the next 5 seconds and proceeded to facepalm
@gigabit6226
@gigabit6226 3 жыл бұрын
HAHAHAH
@subliminalcastillo2126
@subliminalcastillo2126 3 жыл бұрын
I can't count how many times I've done that. I even gave up for a couple days on a project before because of that. lmfao.
@friidaperez3239
@friidaperez3239 3 жыл бұрын
didnt understan, what do you mean?
@not_herobrine3752
@not_herobrine3752 3 жыл бұрын
the life of a programmer is laced with painful inconveniences
@dwaghe2444
@dwaghe2444 3 жыл бұрын
LMAO
@kylewalker8907
@kylewalker8907 4 жыл бұрын
Hey Brackeys, I know this is an old tutorial, but I got a question: This works just fine until I build and run my project. Everything works fine in the editor but no save information carries over when ran on build... any suggestions?
@Thomason1005
@Thomason1005 4 жыл бұрын
i think Application.persistentDataPath returns a different path when buildt, this is so your editor save is separate from your buildt game save.
@zacharywalker-liang7319
@zacharywalker-liang7319 4 жыл бұрын
Have you found the solution for this? I have the same issue.
@Brian-vs9sd
@Brian-vs9sd 5 жыл бұрын
You could add an extension method to the vector3 class called ToFloatArray, that returns a float array so you don't have to worry about conversions everywhere
@ziadmahmoud1999
@ziadmahmoud1999 Жыл бұрын
best brackeysss missed you so much come back for even vlogs only we want to see you more
@ashir.javed6
@ashir.javed6 4 жыл бұрын
2:48 Has no one noticed the binary file depicted actually has Hexadecimal values written on it :3 but still jokes aside Great tutorial! thanks man!
@Beaubacon
@Beaubacon 4 жыл бұрын
need some help. This wouldnt work when I built to android
@tommywood5337
@tommywood5337 5 жыл бұрын
Love the video, super helpful, totally know what to do now, really helpful, thanks! :)
@Karim-id3ke
@Karim-id3ke 4 жыл бұрын
this guide saved probably many days of my life keep it up!
@LucasWithAC
@LucasWithAC 4 жыл бұрын
how do you do load a save/game if there isn't one to begin with?
@marioaviles19
@marioaviles19 4 жыл бұрын
You don't, it will just return null. that was what the else{ return = null} thing was in the LoadPlayer method , I believe. But I'm pretty new to this
@codyhusky9335
@codyhusky9335 5 жыл бұрын
Great to see a tutorial on this. I'll definitely use this one day. A side note though Brackeys. You should teach better C# practices... 1. Consider using the `var` keyword, this allows more flexible code, faster to write and reads and sounds better than `Stream stream = new Stream()`, so repetitive! 2. Don't be scared to throwing errors, instead of returning null, the caller should be responsible for handling errors and it doesn't know what happened if you just return null. 3. Consider using `using` statements, they encapsulate any disposable object (such as your stream) and dispose it automatically when the scope closes. 4. Use native .net functions such as Path.Combine, dont assume paths don't end with slash or even that the OS uses slashes, this function will handle that all for you. Would love to see you teaching these, just one step closer to nicer code in Unity...
@g3ck037
@g3ck037 5 жыл бұрын
The first tip is not good in my opinion, as i wouldn't want to debug your code if you regularly use 'var' (unless it's for variables that exist only for 2 lines of code).
@codyhusky9335
@codyhusky9335 5 жыл бұрын
I was doubtful too before I started using it. Turns out it's basically never a hindrance. The IDE will tell you the type if you hover over it and if you don't want to do that the initialization is usually very close by. Not to mention the name usually tells you anyway!
@Sebastian198910
@Sebastian198910 5 жыл бұрын
That’s not all. From a clean code perspective there is much to improve von brackys. For me it even looks odd that he copies single lines instead of just doubling them with Ctrl + D. As someone who learned and deals with IODA architecture all the time and who only codes the whole day, I find his C# skills average as max and his .NET knowledge as basic. But when it comes to unity he simply overcomes my knowledge by the same amount at least.
@dannehsg978
@dannehsg978 5 жыл бұрын
Sebastian Kruse yeah he purposely make them as basic as possible for beginners or intermediates like me because my school just started using unity
@lipnyCzlowiek
@lipnyCzlowiek 5 жыл бұрын
I am not sure how using var is a better practice. C# is strongly typed language for a reason.
@cubyte4640
@cubyte4640 3 жыл бұрын
Great tutorial! this was very important thing for my game. thank you very much
@ilsignorfesta7716
@ilsignorfesta7716 5 жыл бұрын
thanks man, you helped me so much
MULTIPLAYER FPS PROJECT in Unity
11:14
Brackeys
Рет қаралды 402 М.
The Future of Game Development
8:58
Brackeys
Рет қаралды 1 МЛН
Glow Stick Secret (part 2) 😱 #shorts
00:33
Mr DegrEE
Рет қаралды 42 МЛН
Normal vs Smokers !! 😱😱😱
00:12
Tibo InShape
Рет қаралды 39 МЛН
skibidi toilet 73 (part 2)
04:15
DaFuq!?Boom!
Рет қаралды 32 МЛН
Better Save/Load using Data Binding in Unity
18:47
git-amend
Рет қаралды 8 М.
Learning C# In A Week... Otherwise I Fail University
9:04
Be CAREFUL with Scriptable Objects!
8:27
Code Monkey
Рет қаралды 73 М.
Save Game Data with 2 lines of code and CloudSave
11:45
Jason Weimann
Рет қаралды 3,6 М.
HOW TO GAME JAM!
9:01
Brackeys
Рет қаралды 262 М.
How to program in Godot - GDScript Tutorial
58:10
Brackeys
Рет қаралды 165 М.
How to make a Video Game - Godot Beginner Tutorial
1:17:12
Brackeys
Рет қаралды 723 М.
How to make 2D GLOW in Unity!
15:56
Brackeys
Рет қаралды 578 М.
Glow Stick Secret (part 2) 😱 #shorts
00:33
Mr DegrEE
Рет қаралды 42 МЛН