SAVE & LOAD SYSTEM in Unity

Поділитися
Вставка
  • Опубліковано 29 вер 2024

КОМЕНТАРІ • 1,8 тис.

  • @lilmonster5684
    @lilmonster5684 5 років тому +2666

    "So you've made a game and it played nicely.."
    Me: umm

    • @OutOfNameIdeas2
      @OutOfNameIdeas2 5 років тому +401

      *Syntax error on line 142*
      Me: *Code ends at line 78* ?!?!?!

    • @QuietSnake-xs5vx
      @QuietSnake-xs5vx 5 років тому +28

      @@OutOfNameIdeas2 xD

    • @emeralaxy850
      @emeralaxy850 5 років тому +131

      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 5 років тому +75

      ​@@emeralaxy850​ *one missing semicolon*

    • @minecraftermad
      @minecraftermad 5 років тому +34

      @@JW-oe6nw 2 missing brackets

  • @PTurtle
    @PTurtle 3 роки тому +20

    Me - nowhere near completing my game
    Also me - *I think I should add a save function*

    • @joeman123964
      @joeman123964 3 роки тому +1

      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 3 роки тому +1

      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"

  • @Bonnie39
    @Bonnie39 2 роки тому +2

    I'm having a bit of trouble getting the load function to work automatically. I tried adding a script to a gameobject that calls the load function on void Awake() but that doesn't seem to be doing anything. Could it be that saving isn't working correctly either? I'm not quite sure what exactly I'm doing wrong.

  • @janozahor4130
    @janozahor4130 2 роки тому +2

    what if I want to save in different scene?

  • @cptshini
    @cptshini 5 років тому +23

    YEEESSSSSS FINALLY
    det tog dig lidt for lang tid :D

    • @zuccdanelia
      @zuccdanelia 5 років тому +6

      I'm a simple man. I see Danganronpa, I like

    • @seireiart
      @seireiart 5 років тому +3

      @@zuccdanelia Same here

    • @scrub2657
      @scrub2657 5 років тому +2

      Tog väldigt lång tid

  • @dc37wwe2kmods
    @dc37wwe2kmods 5 років тому

    Thank you so much for this! :)

  • @mrheadshotzz4637
    @mrheadshotzz4637 5 років тому

    Brackeys, I am a huge fan of your channel, and I have one question for you on the topic of Saving and Loading player progress. Your save and load system works, but does it work as a built standalone project? I used playerPrefs for my game, and it worked perfectly until I built it as a standalone. Then. when I exited the standalone game, and came back later, it didn't save any of my progress. Do you know why this is happening, but if you don't, will this happen if I use your "Binary Conversion" method?

  • @GameDevGeeks
    @GameDevGeeks 4 роки тому

    That was good like always 👍

  • @thepokednoob9497
    @thepokednoob9497 4 роки тому +1069

    Brackeys: "And now, we are ready to try it out"
    Me with 5 errors: *"yes"*

    • @harshvardhanmisal2255
      @harshvardhanmisal2255 4 роки тому +2

      @TRAGE GAMING he probably missed a lot of simple and basic stuff

    • @subzero4787
      @subzero4787 3 роки тому +8

      me 1 error

    • @harshvardhanmisal2255
      @harshvardhanmisal2255 3 роки тому +9

      @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 роки тому +6

      You're lucky, but I am now with 13 errors.

  • @shahryar50
    @shahryar50 4 роки тому +327

    I feel a little sad watching the videos now knowing they stopped

  • @maythesciencebewithyou
    @maythesciencebewithyou Рік тому +6

    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.

    • @ShashankSingh-lc6qc
      @ShashankSingh-lc6qc Рік тому

      what is the alternative then

    • @maythesciencebewithyou
      @maythesciencebewithyou Рік тому +1

      @@ShashankSingh-lc6qc Save it as a json file. Just look for some tutorial. "unite save as json"

    • @ShashankSingh-lc6qc
      @ShashankSingh-lc6qc Рік тому

      @@maythesciencebewithyou Thanks, is there any way to encrypt that file so no user can change my file?

    • @maythesciencebewithyou
      @maythesciencebewithyou Рік тому

      @@ShashankSingh-lc6qc Of course you can encrypt your files if you want. Just google some ways to encrypt. A plain Json file would be simple to change for everybody, so some level of encryption wouldn't be bad if you are worried about people cheating. However, be aware that even with encryption, some people will still find ways to cheat.

    • @ShashankSingh-lc6qc
      @ShashankSingh-lc6qc Рік тому

      @@maythesciencebewithyou you are right. It is really weird that this kind of misinformation is available. Thanks for informing about the risk factor.

  • @sykoo
    @sykoo 5 років тому +1750

    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 років тому +4

      What about the LD game with u and noa :D

    • @anubhavgupta3562
      @anubhavgupta3562 5 років тому +1

      I had given the suggestion of this on your channel also

    • @nein3405
      @nein3405 5 років тому +16

      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 5 років тому

      Wheres the rpg tutorial

    • @redbepis4600
      @redbepis4600 4 роки тому +1

      yeah! I made clicker game but everything whould just reset

  • @AlanDarkworld
    @AlanDarkworld 5 років тому +370

    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 років тому +47

      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 років тому +28

      @@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 років тому +17

      @@AlanDarkworld Using is more beginner friendly

    • @s-.-8821
      @s-.-8821 5 років тому +5

      I am getting fucked cause of that

    • @DynaZor
      @DynaZor 5 років тому +6

      Can you please give an example? I don't know how to do that...

  • @Zicore47
    @Zicore47 4 роки тому +134

    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 роки тому +4

      Thanks man. Yeah, tutorials like this need review. Combine is a crucial thing to point out for OS compatibility.

    • @Devorkan
      @Devorkan Місяць тому

      Yeah I like Brackeys' videos for learning Unity but as a developer myself I recognize his code quality isn't the best

  • @DukaSoft
    @DukaSoft 5 років тому +58

    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 роки тому +2

      hahaha good point

  • @badgamedevreacts3855
    @badgamedevreacts3855 4 роки тому +75

    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 4 роки тому +1

      HAHAHAH

    • @subliminalcastillo2126
      @subliminalcastillo2126 4 роки тому +7

      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 роки тому +1

      the life of a programmer is laced with painful inconveniences

    • @dwaghe2444
      @dwaghe2444 3 роки тому +1

      LMAO

  • @jimdim2222
    @jimdim2222 5 років тому +74

    *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 роки тому +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 роки тому +3

      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.

  • @DustyTrailsDev
    @DustyTrailsDev 9 місяців тому +2

    BE CAREFUL USING THIS TUTORIAL!
    The binary save method has been depreciated because it is not safe, and can be used by hackers to run code on your device. Be careful!

    • @tek_ark
      @tek_ark 8 місяців тому

      is this true?

    • @vatsoffice
      @vatsoffice 7 місяців тому

      yes@@tek_ark

  • @CouchFerretmakesGames
    @CouchFerretmakesGames 5 років тому +178

    It was simple enough, but also in-depth as well! Thanks!

    • @kodo777
      @kodo777 5 років тому +7

      again, seeing you in places I didn't expect

    • @CouchFerretmakesGames
      @CouchFerretmakesGames 5 років тому +7

      @@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.

  • @bonestudios7777
    @bonestudios7777 9 місяців тому +37

    5 years in and still this is one of the best save and load system tutorial that I found out there.

    • @Chubzdoomer
      @Chubzdoomer 6 місяців тому

      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 6 місяців тому

      thanks for the comment. I am about to start and needed to know if it still fits.

    • @Chubzdoomer
      @Chubzdoomer 6 місяців тому

      @@imtiazsabree6562 It doesn't. DO NOT use BinaryFormatter. Microsoft themselves advise against it.

    • @Plexity_WasNotFound
      @Plexity_WasNotFound 4 місяці тому +1

      does this work for everything? like no matter what type of game you have?

    • @Blinkers2007GameDev
      @Blinkers2007GameDev Місяць тому

      same

  • @creationsmaxo
    @creationsmaxo 2 роки тому +17

    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).

  • @rmt3589
    @rmt3589 Рік тому +2

    How can you save a procedurally generated world?

  • @TheDragonCat99
    @TheDragonCat99 4 роки тому +192

    “Because they’re in binary”
    * shows hexadecimal file *

    • @laplongejunior
      @laplongejunior 4 роки тому +12

      To be honest, absolutely nobody would read a file in binary except for showing off.

    • @equation1321
      @equation1321 4 роки тому

      laplongejunior large brain

    • @laplongejunior
      @laplongejunior 4 роки тому +8

      @@equation1321
      A good developer is a lazy one :P

    • @equation1321
      @equation1321 4 роки тому +1

      @@laplongejunior yea

    • @xfata1err0rx89
      @xfata1err0rx89 4 роки тому +4

      @@laplongejunior Agreed. I'm a programmer and you always have the new programmers that think they're doing something by programming that way. lol As you said, it's nothing more than to show off, but overall a waste a time. With this video though, if your game is offline it doesn't truly matter much; easy enough to just access memory to manipulate those systems. If your system is online, anything important is on the server database anyways and checked against anything you try to manipulate locally. As best as possible at least, that's the problem with aimbots/wallhacks since it's locally controlled so it's kinda like having to always scan for viruses and keep blocking how they're doing it; not impossible but insanely annoying relatively speaking. Personally, if you bought my single-player game, manipulate it however you feel like since it's yours now. lol

  • @Georghiou2D
    @Georghiou2D 5 років тому +2

    In the PlayerData script, how does that script find the Player? Like, its a serialized class, so i cant just grab the GameObject

  • @Unknown-bm5ui
    @Unknown-bm5ui Рік тому +37

    You are the godfather of programming for me. Thank you so much for everything you do.

  • @noormuhammad5923
    @noormuhammad5923 3 роки тому +37

    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 роки тому +6

      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

  • @CoolJosh3k
    @CoolJosh3k 5 років тому +21

    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 5 років тому +13

      15:00 add
      if(data != null)
      {
      // Attributing the variables
      }

  • @IronDizaster
    @IronDizaster 5 років тому +14

    Could you maybe in the future make a tutorial on the " Easy Save " plugin you mentioned later in the video?

  • @speedyzolt
    @speedyzolt 5 років тому +18

    You’re amazing. As an artist I find your tutorials easy to follow. Thank you and your team of people. UA-cams best Unity programming specialist. I’m inspired please continue this channel.

  • @UltraHylia
    @UltraHylia 5 років тому +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.

  • @christofflinde
    @christofflinde 4 роки тому +61

    "So I've gone ahead and set up a simple example level"
    Me: uuhhmm

  • @saras2743
    @saras2743 3 роки тому +16

    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 роки тому +1

      TYSM i had this exact problem and this fixed it

    • @OcnarfPro
      @OcnarfPro 3 роки тому +1

      That is how you make a constructor

    • @MrPersonGuyPerson
      @MrPersonGuyPerson 6 місяців тому

      When I did that it gave me an error in SavePlayer script

    • @saras2743
      @saras2743 6 місяців тому

      @@MrPersonGuyPerson is your SavePlayer a script or a function? make sure its in the SaveSystem class

  • @cardsatanywhere363
    @cardsatanywhere363 Рік тому +3

    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.

  • @androvictrayo-dy7eh
    @androvictrayo-dy7eh 7 місяців тому +2

    it's a great tutorial but is confusing when everything is named player and player

  • @tartaro-mk6hv
    @tartaro-mk6hv 5 років тому +12

    Love your tutorials!!
    Can you make a guide on in-game purchases through unity??

  • @scriptbrix
    @scriptbrix 5 років тому +6

    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.

  • @colbysnodgrass3997
    @colbysnodgrass3997 5 років тому +9

    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 11 місяців тому +1

      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.

  • @stellarstudio5495
    @stellarstudio5495 5 років тому +22

    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 років тому +1

      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 років тому +1

      Lost Conflict I made a video using AES to encrypt save data Encrypt Save Games in Unity with AES ua-cam.com/video/SXa6jSW7ckY/v-deo.html that might be of some help

    • @stellarstudio5495
      @stellarstudio5495 5 років тому +1

      @@ahkaay9419 unless it's server side, but that's a whole other story.

    • @diadetediotedio6918
      @diadetediotedio6918 5 років тому +2

      @@ahkaay9419 you can obfuscate code, and using ILCPP, the code turns native

    • @lostconflict9369
      @lostconflict9369 5 років тому

      @@sloankelly Oh ty really appreciate it.

  • @h4z4rd1000
    @h4z4rd1000 5 років тому +51

    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 років тому +5

      @@DynaZor it is missing a bracket :
      using(FileStream stream = new FileStream(path, FileMode.Open))
      {
      // Do Something with the file
      }

    • @mekolaos9341
      @mekolaos9341 5 років тому +5

      I was wondering if there was a "with" keyword in C# like in python. Thanks for the tip !

    • @SafaAlkan
      @SafaAlkan 4 роки тому +2

      *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?

  • @Zethneralith
    @Zethneralith 5 років тому +3

    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.

  • @BrontoKroxig
    @BrontoKroxig 2 роки тому +2

    Remember that BinaryFormatter is obsolete!

  • @jessemauritz1
    @jessemauritz1 4 роки тому +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?

  • @WikiteTV
    @WikiteTV Рік тому +1

    I am getting this error when I try to load the Cash data:
    Object reference not set to an instance of an object
    PlayerStats.LoadPlayerStats () (at Assets/Scripts/PlayerStats.cs:38)

  • @miaoumixed4268
    @miaoumixed4268 4 роки тому +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.

  • @deraminator945
    @deraminator945 3 роки тому +2

    I get 2 Errors.
    first: Save file not found in bla bla bla (so for some reason it can't find the save)...
    second: NullReferenceException: Object reference not set to an instance of an object (this is my SavePlayer() that I put on a trigger)

    • @deraminator945
      @deraminator945 3 роки тому

      Ok so the Errors are fixed only when I have the LoadPlayer() and SavePlayer() on A BUTTON... bad thing is , that because of that, I need that save button on the main game, while the load stays on the menu.... and I tried to call the save function from another script, but the (this) makes trouble...

  • @samriviera6299
    @samriviera6299 5 років тому +5

    I'm just 3 minutes into the video, but why not just encrypt your .json files?

  • @Zukomazi
    @Zukomazi 5 років тому +6

    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!!

  • @ebbevandijk8069
    @ebbevandijk8069 5 років тому +1

    *SOLVED*
    One question how can I change a public int in the player script? For example if I go from scene 1 to scene 2 I want the level to go from 1 to 2. Can someone help.

  • @jonasw7629
    @jonasw7629 4 роки тому +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!

  • @axux4509
    @axux4509 4 роки тому +2

    What if the game crashes somehow while saving? Wouldn't it just corrupt the file and make the player lose all the progress? Wouldn't it be better to keep the previous savefile as backup?

  • @kylewalker8907
    @kylewalker8907 4 роки тому +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 роки тому +1

      Have you found the solution for this? I have the same issue.

  • @ExoticFireIND
    @ExoticFireIND 8 місяців тому +1

    brother,
    file handling in c# ke concept sikhane ke baare me bhi sochna - PLEASE 🙏🙏

  • @toddchavez5374
    @toddchavez5374 5 років тому +61

    Yeeee that was I needed! *thank you Brackeys*

    • @Laiser
      @Laiser 4 роки тому

      Weebs everywhere

  • @MilkyNep
    @MilkyNep 2 роки тому +1

    why should I care about security...?
    I don't give a shit if the players can modify their save or not. They can do whatever they want with them.

  • @BluePhantomGames
    @BluePhantomGames 3 роки тому +3

    Brackey: You can even use an asset called easy save.
    Me go checks out the price:
    69 dollars
    Me who lives in India:
    5000 rs
    Wow

    • @emissaryofcharybdis105
      @emissaryofcharybdis105 3 роки тому

      It's probably better to not be getting too many pre made assets, anyway. Pre made asset abuse is rampant in the Unity dev world and gives the engine a bad name because of it. It's hard as hell to make things from scratch, but it makes it less likely for things to start getting that similar aftertaste of everyone using the same gear. Like guitar players all using the same amp, overdrive pedal, and vintage 30 speaker.

    • @BluePhantomGames
      @BluePhantomGames 3 роки тому

      @@emissaryofcharybdis105 Nah bro i am not using any assets. But i want a good tutorial about player prefs. So that i can save my player health,bullets left etc

    • @PabTSM-OfficialChannel
      @PabTSM-OfficialChannel 3 роки тому

      @@BluePhantomGames player prefs is more for basic stuff.
      it is recommended that you use playerprefs when saving settings and high score, but not health and etc

    • @BluePhantomGames
      @BluePhantomGames 3 роки тому

      @@PabTSM-OfficialChannel You sure?

    • @PabTSM-OfficialChannel
      @PabTSM-OfficialChannel 3 роки тому

      @@BluePhantomGames yes i'm sure.

  • @creativecraftingbhaumik2296
    @creativecraftingbhaumik2296 2 роки тому +1

    I am working on a big project and I am not able to understand some things so can somebody tell me--:
    1. I have to save the game everytime the player clicks quit button and load the saved things everytime I open the game
    2. I want to save inventory system and for eg i placed a bed in my home so how could I save position of my bed and load the bed there when I open game again
    Thank you.

  • @TheGrimmy
    @TheGrimmy Рік тому +1

    I super appreciate this! It was very quick and easy to follow. I have a game with a LOT of variables to save. Is there a way to do a "save and quit" where I can check if the data is saved before closing the application? Like a code to do a if{SaveSystem.SavePlayer == true) {Application.Quit();} I just don't know how to check if the data was indeed saved..

  • @romanglinnik8073
    @romanglinnik8073 5 років тому +4

    That momet, when you've recently finished your Saving script and a tutoriel about saving/loading by Asbjorn shows up👍

  • @TortoRacoon
    @TortoRacoon 5 років тому +1

    how do you (for example) make it go from the main menu to open a scene with the saved data loaded? that is how loading data actually works, not really changing values in the same scene

  • @blokbustr
    @blokbustr 5 років тому +8

    I’ve seen Nintendo use that binary system a lot

  • @silentgamer2555
    @silentgamer2555 4 роки тому +1

    your code giving me this shit eror
    error CS0176: Member 'Player.scorevalue' cannot be accessed with an instance reference; qualify it with a type name instead

  • @bckb604
    @bckb604 4 роки тому +6

    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 4 роки тому

      Couldn't quite understand. Can you explain more. Just a little more detailed. Thanks

    • @cmpmusic9389
      @cmpmusic9389 4 роки тому

      @Ethan Bettenga

    • @bckb604
      @bckb604 4 роки тому

      @Ethan Bettenga I ended up using playerperfs, but I would love to see your solution for this!

    • @cmpmusic9389
      @cmpmusic9389 4 роки тому

      So do I

  • @priyankbhikadiya9079
    @priyankbhikadiya9079 4 роки тому +1

    hello sir i got problem
    when i write this code there is no error but when actually use this code and hit save button then there are
    two error shows
    1. safe file not found
    2. null reference Exception
    please sir help me to solve this error

  • @seb4542
    @seb4542 3 роки тому +4

    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

  • @danio583
    @danio583 4 роки тому +1

    i have the error CS1061 in PlayerData.cs
    can i have some help plz??

  • @Gapthrosnir
    @Gapthrosnir 4 роки тому +8

    This is perfect timing! I was about to start working on a save system over the weekend.

  • @evilglitch6546
    @evilglitch6546 4 роки тому +1

    i need help what unity player do you use like how to download the unity player and attach the easy save to it or like that for free or payed version because i dont know what you even using
    *Please Help*

  • @xipheonj
    @xipheonj 4 роки тому +13

    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.

  • @neftalito
    @neftalito 4 роки тому +1

    NullReferenceException: Object reference not set to an instance of an object
    Help, data returns null when loading

    • @ilariabruni9815
      @ilariabruni9815 4 роки тому

      I think you have ti add your public variables on the ispector

  • @xXrandomryzeXx
    @xXrandomryzeXx 4 роки тому +7

    I really wish that every unity tutorial was by you, like you explain so well and it's so fun learning by you.

  • @devgameswithbark8207
    @devgameswithbark8207 2 роки тому +2

    why do you stop youtube please continue

  • @_Daus_
    @_Daus_ 5 років тому +4

    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 років тому +1

      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/

  • @emilemil1
    @emilemil1 3 роки тому +1

    I'd argue that save data should almost never be in a binary format, it should always be easily modifiable for the player. A player that wants to cheat will always be able to do so no matter what you do, at least for as long as the save state is stored locally, all you're doing is making it more of a hassle. Besides, they own the game, should they not be able to do with it as they wish? Besides cheating there are also several other great reasons to modify the save file.
    I'm sure we all have experienced various breaking glitches in games, like quests that refuse to finish, or NPCs that never spawn. Usually these are related to some state that failed to update properly, and that state is probably stored in the save file, so it can be fixed by modifying it.
    Some games have multiple endings that require you to fulfill certain criteria throughout your playthrough to see a particular ending. It can be extremely frustrating to try for one of these endings only to realize that you missed a criteria, especially if you don't have a save point to go back there or if it's many hours in the past. Modifying the save file is a way out.
    The only legitimate reason to use a binary format in my opinion is if you need to save data that can't be made human readable. For example if you have a sandbox game where the player builds structures, such as Minecraft. The data required to store those structures is far too complex and probably heavily compressed, you would need a tool to modify it either way so there's no point in storing it in a human-readable format. Even then you should reserve binary files for just this data, and the rest should be in something like JSON or plain text key-value pairs.
    I'd even go as far as to suggest that most of your actual content, like enemies, items, and level layouts should also be stored in human-readable formats. This makes the game very easy to modify even without having access to the Unity project, which is great for fostering a modding community. It might not be relevant for when you're building a small platformer or whatever, but it's good to practice and get into the habit for when you move onto bigger projects.

  • @Beaubacon
    @Beaubacon 5 років тому +4

    need some help. This wouldnt work when I built to android

  • @Meteor2022
    @Meteor2022 2 роки тому +1

    Can't save anything because System.UnauthorizedAccessException: 'Access to the path............. then it goes on to say the file path and that it's denied. I have tried everything in my knowledge to let it create files but t just doesn't work.

    • @Meteor2022
      @Meteor2022 2 роки тому

      Update: I got it to work, dumb mistakes do exist and this was one of them.

  • @nighrix303
    @nighrix303 4 роки тому +3

    If your Game dont find the Files
    Do That:
    In your "GameManager" Script
    Void Awake:
    try {
    load...();
    }catch {
    save...();
    load...();
    }
    // So if you dont Find the Files the Game creates the File and then load it again
    // Idk if you need load...() at the End but ... you know

    • @SafaAlkan
      @SafaAlkan 4 роки тому +1

      *Does this script allow the player to resume on which stage he / she stayed in later?* Do you know?

    • @nighrix303
      @nighrix303 4 роки тому +1

      @@SafaAlkan yes but its only for loading data you need to follow the steps in the video for saving

    • @nighrix303
      @nighrix303 4 роки тому +1

      @@SafaAlkan But do it in a awake() function or your game could get some logic bugs

    • @nighrix303
      @nighrix303 4 роки тому +1

      If you have any other Question just ask

  • @raphaelzwander481
    @raphaelzwander481 4 роки тому +2

    I forgot to delete the ":" after the "public static class SaveSystem" and couldn't figure out why it wants a type for so long xD
    But it works now : )

  • @MaskedImposter
    @MaskedImposter 5 років тому +8

    This tutorial fills me with determination.

    • @daredeflon662
      @daredeflon662 4 роки тому

      Your health has been fully restored.

  • @MoogieSRO
    @MoogieSRO 2 роки тому +1

    9:00 - Would it make sense to pass the Player object by ref here, to avoid making a new temporary copy of it during the save process? Or can you not pass by ref in Unity? (I've not started any Unity dev yet, just watching these videos to get a feel for it)

  • @LucasWithAC
    @LucasWithAC 5 років тому +4

    how do you do load a save/game if there isn't one to begin with?

    • @marioaviles19
      @marioaviles19 5 років тому

      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

  • @CellarPhantom
    @CellarPhantom 3 роки тому +1

    When trying to save, I'm getting a "SerializationException: Type 'PlayerData' in Assembly [...] is not marked as serializable" :(

    • @CellarPhantom
      @CellarPhantom 3 роки тому

      omg I missed the "very, very important" attribute at 6:50

  • @ebanwolf6288
    @ebanwolf6288 5 років тому +3

    Hey man ur Awesome, Im ending a work of my carreer and it videos help me a lot. Congrats from Spain !

  • @roguebanshee
    @roguebanshee 4 роки тому +1

    Why does a certain group of developers fear players editing save file data for single player games/campaigns? If players want to cheat/mod they will find a way, so why make that process obnoxious (outside MP scenarios)?
    With a hard to read savefile, players who would be interested in cheating/modding are instead going to find a trainer or a tool like Cheat Engine to mess around with things during runtime. And unless you do some work trying to obscure your player data during runtime, these tools are likely going to allow the player to do far more than what they could with editing a save file.
    So why not just let this group of players have easy access to messing around instead of putting in a lot of work making your own parser for a format. And if you're just using the built in formatter, you're not even making it hard to read for anyone with minimal C# experience, you're just making it hard for yourself to quickly check whether the game saved all the apropriate data.

  • @marjulbalcon3128
    @marjulbalcon3128 5 років тому +4

    Hi, what if the load button is in another scene. what should i do?

    • @marjulbalcon3128
      @marjulbalcon3128 5 років тому +1

      I create an an object that wont be destroyed and inside that i condition something if condition meet i put my load in my characterstats awake.

    • @festiveFurry
      @festiveFurry 5 років тому

      What did you do? I really need to know

    • @rufius4050
      @rufius4050 3 роки тому

      @@marjulbalcon3128 i need to know :D

  • @CHITUS
    @CHITUS 2 роки тому +1

    One day I'm going to understand all of this, and it's going to be glorious

  • @BakasuraOfficial
    @BakasuraOfficial 4 роки тому +3

    5:10 - Visual Studio has a shortcut for creating this class, simply type: "ctor" and press TAB twice and it will generate an empty constructor class, but if you have alot of properties it's better to use "CTRL + ." and select "generate constructor", this way it will bind the values to the properties of the class, and for more organization, typing "///" and TAB twice above the class it will create a commented code with the right syntax with all the properties that's the constructor takes and their implicit type, so that with IntelliSense when using the class, you just mouse over the property and with will show you a resume of the class (it also supports own comments on the class, like "Note: this class ..."
    Hope someone finds it useful

  • @TortoRacoon
    @TortoRacoon 5 років тому +1

    if for example, we have a game like Age of Empires where the whole scene is the progress, is there a way to just have like a "picture" of the game and save that, and when ever the players opens the game, it goes to the last moment where the game was saved?

    • @CamoflaugeDinosaue
      @CamoflaugeDinosaue 5 років тому

      I doubt something like that is supported in Unity. It would probably result in large file sizes in most cases.

  • @texturem0nkey
    @texturem0nkey 4 роки тому +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.

  • @ibrahimaltaha3186
    @ibrahimaltaha3186 4 роки тому +1

    You did it in 3 steps , the middle step is totally pointless. Lets review: firs your created a mono code inside the player that register things [level, health, position]. OK great, after that, you created a separated class called player that will take the variable from the mono behavior that is inside the player, then created another class that transform this class into binary file when you click SAVE. ok , when you click load , you take the binary file then you put it inside the player directly,,,,, HOLD ON WAIT A SECOND, what was the purpose of the second step? which is the class that is called player !!!!. couldn't you simply just take the data from the mono and store it as binary? would it be easier to load and save afterward ?

    • @ibrahimaltaha3186
      @ibrahimaltaha3186 4 роки тому +1

      i did it in 2 steps, the mono behavior player is simply (mono, and serializable), take it and store it , and when needed? load it and fix it

  • @shaiavraham2910
    @shaiavraham2910 4 роки тому +4

    11:14 "Let's also create a variable for loading some data..."
    Me: I don't know why, but something makes me think that it's a method and not a variable.

    • @davidg5630
      @davidg5630 4 роки тому +1

      You're right its a method that will return a value to a variable. He just mixed up his words there.

    • @killereks
      @killereks 4 роки тому

      Its a function not a method

    • @shimmel4738
      @shimmel4738 4 роки тому

      @@killereks it's the same thing lol. Just one has a return type and the other doesnt lol

    • @killereks
      @killereks 4 роки тому

      @@shimmel4738 it is not, a method is a procedure which is a void and function is a method that returns a variable (from maths)

    • @shimmel4738
      @shimmel4738 4 роки тому

      @@killereks that's pretty much what I said.

  • @truebillionaire7016
    @truebillionaire7016 4 роки тому +2

    OK it works for the layer, but i cant recreate a Savesystem for a simple other variable! I need a savesystem it for my Questsystem, there are INT variables called QuestXXXX!

  • @greenbear9790
    @greenbear9790 4 роки тому +3

    Is playerdata gonna be deleted when the game has uninstalled?

    • @kizonyoutube
      @kizonyoutube 4 роки тому +1

      It depends, if its a 3rd party installer/uninstaller then it wont uninstall something that wasnt already included, unless its in the folder you specified when setting up the installer. You could include the player data file but then it'd be in an obvious location. The best solution is to make a custom installer/uninstaller so you can make sure to uninstall things added later on. Some 3rd party software probably allows you to specify to look for a new file somewhere else to uninstall, I wouldnt know.

  • @maceeiko
    @maceeiko 3 роки тому +1

    15:20
    You could write:
    transform.position = new Vector3(data.position[0], data.position[1], data.position[2]);

  • @V.Z.69
    @V.Z.69 3 роки тому +3

    12:49 PlayerData LoadPlayer() --- is read and has errors. So I waited for the video to go onward... Is "PlayerData" a system Variable? So at time 13:56 I look at your console and see Assets: Player, PlayerData. I don't have these assets. Is this a GameObject called PlayerData? The tutorial? The tutorial here is the same everywhere. Do you guys always use the same format? I am not a Native Born Unity Human, I cam from World C, a realm of memory and pointers and buffer handling. Joking aside. It seems that you all are using a Cookie Cutter system of programming ( some people like to say coding, but a coder is not a programmer ). I digress. So, *what is PlayerData?* Please and thanks! I was waiting for you to click onto PlayerData (script or object?) so I could see what your code referst to. Very stressfull, because this is the 3rd video that does exactly the same thing on 3 channels and no divulging. So it seems like a Unity Cookie Process that I am missing.

    • @nextProgram
      @nextProgram 3 роки тому

      PlayerData is the class he made a couple minutes earlier in the video

  • @areg_arzumanyan
    @areg_arzumanyan 4 роки тому +1

    BinarySerializer is not working!
    Who can help me?

  • @bladescreed
    @bladescreed 3 роки тому +6

    Just some friendly advice I was running into an IO Exception when loading or saving too quickly, Stream.Close() was taking too much time and I would eventually try and open while it was trying to close, an easy solution was
    using (FileStream stream = new FileStream(path, FileMode.Create))
    {
    formatter.Serialize(stream, obj);
    }

  • @In-N-Out333
    @In-N-Out333 5 років тому +31

    Show us how to make a fog of war effect for an rts game.

    • @moltak115
      @moltak115 5 років тому +4

      Doesn't seem that much complicated. Sounds like just checking if in your view area then light up and make enemy unit visible.

    • @blazerivers3000
      @blazerivers3000 5 років тому +7

      You good bro?

    • @uba754
      @uba754 5 років тому +3

      I'd like to use it for a map, sort of like the map in Minecraft. Starts off blank but gets revealed as the player passes through.

  • @DRsewage
    @DRsewage 4 роки тому

    I'm testing and working on 3D puzzle escape horror game And i just realise how complex have to be saving system to save all of the states of objects.. from player status to eveyfucking light sources on map destroyed while playing..
    Do you guys have any solutions that might help If i wanna save status of all objects in map/scenes? It has to be a way instead of writing tons of code for saving every object on the map..

  • @47Mortuus
    @47Mortuus 4 роки тому +9

    The PlayerData class can be done WAY better.
    Make it a PUBLIC NESTED class WITHIN the Player class. That way your constructor can access the root class' (private) variables and thus you don't need to pass in those variables when instantiating the data class, which can be especially annoying with real world classes that hold 20 to 100 values.
    Furthermore, you can generically call such nested classes "Data". So...:
    new Player.Data().Save();
    Way more elegant, especially since you don't need to create to seperate scripts.

  • @pectoralismajor1097
    @pectoralismajor1097 5 років тому +2

    Just what I needed. Also good thinking by the Unity devs to make "Application.persistentDataPath" for easy use.