Search Unity

Serialization - Why Should I Use It

Discussion in 'Scripting' started by ippdev, Mar 15, 2017.

  1. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    I have been coding for about two decades and started in Unity using UnityScript as that was the paradigm way back then. Having transitioned over to C# for some time now I have my certain practices to keep a handle on things during development like making all my variables that I need to see values of for tweaking or comparing deltas between states as public so I can review them in the Inspector in Edit Mode or Runtime. I later, after zeroing in on that magic value make the variable private and no longer reviewable in the Inspector as it is what it needs to be and won't change. I have never Serialized any object or variable except in a few Editor scripts and it never seemed to cause any errors or warnings and the application worked as I wanted it to, even with massive data sets. So why would I want to or need to serialize anything? Is this just more needless compsci MS backflipping for no good reason or am I missing something important?
     
  2. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Serialisation is absolutely vital for saving and loading, if you are making games that won't ever require saving and loading to work then yes, you could potentially need never have to learn it. However you will find that if you plan on scaling up your projects and make any kind of progression based game that lasts longer than a couple of hours you will be extremely limited.

    Adding to that, gamers will be extremely frustrated if you develop a longer game and they can't save various things. I remember seeing one game on steam and what was interesting about it was that it was a quite small game with progression in it but the fact that the game had no saving and loading at all meant that the gamers were extremely frustrated with it and leaving lots of negative reviews just because the developers hadn't put it in.

    I can tell you now that I spent quite a few months awhile back digging for as much information I could find just on the subject of serialisation and so on and finally having up to date information on it all was a relief.
     
    Last edited: Mar 16, 2017
  3. Dave-Carlile

    Dave-Carlile

    Joined:
    Sep 16, 2012
    Posts:
    967
    Technically any time you have something show up in the editor you're taking advantage of Unity's built in serialization. The only time you have to do custom serialization in the editor is if you're using a type that isn't supported natively.

    Otherwise, like @Lethn said, if you want to save and load game state you need to come up with some sort of serialization. That can be a completely roll-your-own thing like just writing a few values to a file, or using the annoyingly complex .NET serialization that relies on reflection and the like. I usually roll my own.
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    You could also just decorate the field with the SerializeField attribute and always leave it private. While your process works great for you, it wouldn't scale to a team of programmers. How would I know if you want a particular member to be public (and therefore I can use it in my code) or if you just have it public while you tweak it and will eventually make it private (in which case the code that I wrote referencing your public member no longer compiles).
     
    Suddoha likes this.
  5. Xarbrough

    Xarbrough

    Joined:
    Dec 11, 2014
    Posts:
    1,188
    Serialization must be used if you want to save runtime game state.

    Additionally, serialization of editor data makes sense, because you can tweak variables via the inspector without having to change hardcoded values and recompile. This is almost always desired in one form or the other when working on bigger projects with multiple people. You can't afford to wait minutes for a recompile when tweaking gameplay values and you don't want to cause changes to source files, when it's not related to a programming task. Generally, you can program a system and hand it over to designers to tweak values in the inspector, just like the Unity editor works.

    If you're working alone on a small project it might not make a big difference.
     
  6. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789
    Serialization is needed for:
    - saving and loading settings;
    If you use player prefs, that's doing serialization for you, but you have no control over what parts get serialized and how, and eventually when your data-types become a little more complex you'll notice that it will just plain stop working because it can't handle some types and setups, for example event handlers can't obviously be serialized automatically.

    - save games, literally impossible to get a "save game system" that will work reliably, how could it possibly restore all the references between the objects, or know what to save and what to skip.
    unless you want a 600MB save game file haha

    - networking (obviously, but unity does it for you unless you override the serialization of the view...)

    - objects/units/npcs in your game once it reaches a certain size. I think you could make a medium sized game without saving your stuff in custom files, so just using unity prefabs for everything, but sooner or later you'll run into all sorts of dumb problems.
    Unity will start lagging, your levels/zones will become pretty convoluted, and you will eventually run into limitations of the prefab system so you'll have to roll your own management system that's specific to your game anyway...

    For settings I'm usually using json for my stuff.
    Networking I leave to UNET unless there's specific things like my inventory system or spell casting where I need better control to optimize those things... like when the stuff unity does normally would take too much bandwidth.

    does that make it more clear?
     
  7. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    OK.. Great answers folks. I know i need to but just where and how is a bit of a mystery. So I have a bunch of class variables. Can I just put [System.Serializable] at the top like i have seen alot or do i have to header each variable with [Serializable]? What is best practice here? There is already a CSV loader and Revit file parser with the system i am currently reworking.
     
  8. Stardog

    Stardog

    Joined:
    Jun 28, 2010
    Posts:
    1,913
    It can also let you view non-monobehaviour classes in the inspector.
    Code (csharp):
    1. [System.Serializable]
    2. public class Stats {
    3.     public int strength;
    4.     public int speed;
    5. }
    Code (csharp):
    1. public class Test : MonoBehaviour {
    2.     public Stats stats;
    3. }
    That will show a Stats foldout in the inspector. It's good for options/settings where there might be a ton of values/defaults and you want them to be seperated and organised.
     
  9. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    I think people in this thread refer to two different serializations... one being Unity's serialization system that is used in the editor and some others talk about serialization of the actual game state.

    As of the OP, I think the former is the one we should be talking about and @KelsoMRK pretty much nailed it. Use the SerializeField attribute on any encapsulated member you want to expose in the inspector. It might add quite a few lines of code but it's definitely the way to go once you develop something serious.

    Everything else breaks encapsulation and this is often not desired and may introduce troubles. Especially in teams.

    Unitys types are serializable by default, a custom class that neither inherits from MonoBehaviour or ScriptableObject has to be marked explicitly with the System.Serializable. And the you should usually still follow the convention to mark any exposable field with the SerializeField attribute and keep it as encapsulated as possible, for the reasons mentioned above.
     
    AB498 and Dave-Carlile like this.
  10. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789
    you're going about this the wrong way.
    you should instead ask "what do i want to do, and can serialization help me in some way" ?
    and maybe you'll realize the answer is no, ( or maybe yes, we can't know - because we don't know what you're actually trying to accomplish).

    if you don't have some problem that can be solved with serialization then you don't have to make use of it just because... :)

    you said you have a bunch of class variables. If those mono behaviours are attached to prefabs, then they get automatically serialized if they're public. no need to add the attribute.
    basically everything thats visible in the inspector will be serialized automatically for you.


    Just a suggestion here: I think we'd all be better off if you'd just explain what actual problem you are trying to solve, then we can help better.
     
    Dave-Carlile likes this.
  11. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    I don't have any problem. I am just clarifying one of the few things i don't know about C# and the inner working of this, that and the other. Specifically what Serialization does that i may not be doing to begin with.
     
  12. dadude123

    dadude123

    Joined:
    Feb 26, 2014
    Posts:
    789
    In that case maybe start with the basics again.
    Personally I found that when learning something new it's always a good idea to start with something that I already know,and then slowly moving into the new topic.

    For example you could do your own super-sized serialization that uses reflection and only writes an int to a file and later reads it back.

    Or am I misunderstanding you and this thread is completely about using the serialization stuff that unity provides? Meaning, you just want to know what serialization features unity has and how to use them?
     
  13. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Strictly Unity. If I had to code MS business crap for a living I would shoot myself. I have 20 years programming and just never had to use certain things because they do not affect me or I used them but did not know the compsci member waving term for it. I just make lots of games and apps and they work. I must be half decent because I keep getting put in charge of Unity dev.
     
    Jilbarkus likes this.
  14. Hikiko66

    Hikiko66

    Joined:
    May 5, 2013
    Posts:
    1,304
    Serialization allows you to write and load objects in particular states.
    When the instance is saved, it basically writes a blueprint that the language can use to reconstruct the object in that state when you load it again.
     
    Last edited: Mar 17, 2017
  15. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    I guess the biggest takeaway - and maybe a point of confusion for folks is that @ippdev said this:
    after they said this:
    When you expose something to the Inspector - either by making it public or annotating it with SerializeField then you are serializing a variable and GameObjects, prefabs, ScriptableObjects et el are, by their very nature, a series of serialized objects.

    The line of questioning is confusing because the topic is so fundamental to how they engine works. It's like someone asking "Why would I use GameObjects? I just make stuff in the scene and it works."
     
  16. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,998
    Serialization is just a generic language feature that means "data structures know how to read and write themselves." It looks like C# nonsense, and you'll see people who treat it like magic, but it really is a nice trick, and one of the few places where C# has an advantage over C++. See if you can replace some of your hand-written file IO with serialization.

    A review: back in the day, the only way to save data was to add read/write functions to your structs. Those were easy to write, and efficient (you could use what you knew to save space.) You could save pointers with tricks, like using an index to recreate the pointer. When you had inheritance, so weren't sure whether the next Animal was a base Animal or subclass or sub-subclass, you used tricks with leading subclass magic numbers. That was all standard computer programming training back then.

    Serialization is just automating that. Like everything else, an experienced programmer could do a better job, at first. But now the machine does a pretty nice job of auto-generating file read/writes for us. Before, we knew certain vars were temps that didn't need to be saved -- now we do the same thing with a noSerialize tag. The end result still isn't quite as efficient as human-written, but you can just compress the file.

    By now it's pretty standard for an XML file to "be" a struct/class. Browsers even handle it automatically -- the server sends some struct to your page, auto-packaged as XML, auto-unwrapped and jammed right into your javascript struct. I still hand-save (serialize) most of my stuff. It's easy, like an old guy beating a calculator using a slide-rule. But thinking about it, I probably should see if Unity can auto-serialize some of my data in a human-editable format.

    What I'm not sure about is how smart serialization is about storing pointers, or if you can somehow tag that you need a deep copy. And usual disclaimer: like half of everything on Unity forums, I realize this is just a programming Q having nothing special to do with Unity.
     
    Spemble, Ryiah and ippdev like this.
  17. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Love the condescension. I use alot of patterns and methods from trial and error. Knowing the compsci jargon name does not make me much of anything important. I just don't care to remember what the compsci term used is and rare is the tutorial I do. The confusion actually seems to stem from assuming I was running into error prone ways and eliciting responses from self styled experts meant to correct my MS C# truancies. Unity does alot under the hood that is surprising and i have learnt many an interesting thing from a simple question. Carry on:)
     
  18. ippdev

    ippdev

    Joined:
    Feb 7, 2010
    Posts:
    3,853
    Now there ya go. An interesting answer with meat on the bone i can mull over with the who, what, when, where and why's. Thank you. I got a grip on it now. I have written hundreds of XML files and parsers back in the ActionScript 2&3 days.
     
    Jilbarkus likes this.
  19. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Was truly not being condescending - was just clarifying the terminology since it seems like there were a lot of tangential topics swirling around your initial post; while also trying to get at the root of what you were asking.
     
    lordofduct likes this.