So there are many different types of serialization in Unity.
1: Unity Scene GameObject serialization (i.e. setting the transform.position or script value or linking scene objects)
2: Unity Prefab GameObject serialization (i.e. setting values in a prefab’s script)… similar to #1
3: Unity PlayerPrefs
4: UNET Network serialization. [SyncVar] or NetworkWriter.Write(…)
5: Saving GameData to file on drive. (can be any format)
And for each of these there is a read & write.
How do you guys manage all this? Goals being to…
1: Avoid duplication of code
2: Minimize network traffic
3: Making sure save/load file gameData is robust to unknown future version changes (i.e. you have save all 10 keybindings to file, but in a new program version now you have 11 keybindings. if you try and load the array and the array sizes do not match it can crash if not handled properly)
4: Be able to access parts of save/load gameData w/o instancing it (i.e. to access a hero’s name, class, or level to be displayed in hero select menu without actually instancing and spawning a hero prefab)
5: In general not be a giant tangled mess…
I got something working but its pretty complicated. Just wondering if there is an easy or proper way to do all this. Thanks in advance.
Learn, implement and master the art of object oriented programming (OOP). Steve jobs recognized the beauty of it many decades ago, and he wasn’t wrong. OOP is all about containment of code in a multi-dimensional hierarchy. It’s definitely not an easy thing to master, but the core idea is designed around avoiding code duplication by encouraging you to think carefully about what “container” you place your code within.
Like many people I know, I see code as architecture. Once you understand OOP, you’ll likely see it that way too, where you spend a large amount of your time planning where things should go within your multi-dimentional hierarchy of containers, so that they are all placed correctly based on where they will be used and inherited. It’s definitely a form of art, so you can’t expect to learn it over night, but knowing how to use it correctly will fix code duplication issues and much more.
There are a number of strategies that can be used to tackle this, depending on the type of network application that you are building, but to name a few of the major ones:
interest management is probably one of the most useful techniques, but is the most difficult to implement and maintain. It’s ultimately where you only send information to a peer about objects that they are “interested” in, such as objects within a certain proximity or within their vision. This technique is perfect for large-scale networks, such as a network needed for an MMO, where there could potentially be thousands of players on a single server. In this case, you don’t want to have to send information about every player TO every player, and so interest management becomes a very useful technique. Otherwise, it’s cpu cost and complexity make it not worth doing…
combining messages is one of the more under-rated techniques. The idea is that every packet that you send over a network has a header containing information about the packet itself, such as how big it is, the encryption type etc. UDP has an overhead of 8 bytes, while TCP (websockets) have an overhead of 40 bytes. So naturally, sending hundreds of single messages per second rather than one single large message per second can make a huge difference in real-time networking. Unity handles this for you most of the time, however in some cases it’s more efficient to implement this yourself.
delta compression is where you only send information over the network when it changes. For example, why send the x, y and z of a position when only y has changed? Or even worse, why send x, y OR z when none of them have changed? Delta compression is tricky to implement but absolutely essential to ensure low traffic. If you use syncvars, this is handled for you automatically (unity only sends the syncvar when it changes), but you should be doing this for every value that you send over the network.
Other than that, there’s a lot more that you can do. Mainly you want to make sure that you are sending only what you absolutely need to send over the network. For example, in a MOBA type game, you only need to send the target position that the player is walking to when it changes, and have the client walk the character to that position; rather than synchronize the real-time position of the player. So a lot of the time it comes down to thinking cleverly about what it is that you need to “network”, and how you can do it by sending the most-minimal amount of information over the network.
It sounds like you’re attempting to refer to a well-known technique for storing game data… when in actual fact it sounds more like you’ve implemented your own custom storage mechanism that doesn’t do everything you need it to. “data” is a complex topic to which I could go into far too much detail, so to keep it short: whatever storage mechanism you use, it’s your responsibility to make sure that the structure of the data is sound and functional. In your case, it sounds like your data structure isn’t useful enough for what you want to do with it so I would advise to think about how you could change the structure of the data so that you can implement versioning within it.
If you can post the structure of your data in here I could make suggestions on how you could improve it.
Hmm… so by the sound of things, your “data” is some sort of string stored in a text file? Maybe a json object looking something like this?
If this is how your data is formatted, you have no choice but to extract and parse the whole data before you can look at certain parts of it. If you want the ability to deal with data in a highly-functional way, I suggest to look into a better storage mechanism, such as SQL which uses a csv-like storage mechanism allowing for very efficient reading and writing of data (including extracting certain parts of the data). SQLLite is a database engine that you can run at application-level (without needing a database server or anything, can be used in unity) so if you’re interested in sql, I would suggest to look into SQLLite.
Everyone starts off the same way. Like I said above, code is essentially architecture, and becoming a good architect is not easy. So take your time with it, and make sure to learn and grow from what you discover!
Not sure if this should be in the Networking forum section, you might get more answers in something like the Scripting forum section.
Nonetheless, in regards to this
Not too long ago I was working on a save format for 3d models, and I started looking at some of the already made formats.
I ended up going with how the .3ds format works, but I think the FBX format is an upgrade to the 3ds format, so Ill talk a little bit about how I think they both work. I wont go over everything (not that I know it all anyways).
Basically, within your saving format you will put in information letting you know what to expect ahead in the file.
The 3ds format works by having… Chunk header - Which is 2 bytes (UInt16) for the chunk ID (can be any ID you desire), and 4 bytes (UInt32) for the length in bytes of the actual chunk (including the 6 byte header, dont know why it includes, but it does). Variables - ints, bools, floats, strings, etc… The variables must be known and always there in the same order. SubChunks - All the other chunks that you start the process from the beginning.
With this system, you can read a chunk, check its chunk ID and see if you know what the ID is…
If you know the ID, parse the variables that you know are there since you know the chunk ID which means you know how the chunks variables were laid out.
If you dont know the ID, grab its chunks length in bytes and just skip over it to the next chunk.
The flaw is that the variables must not change, but you can pretty much bypass this issue by just wrapping each variable into its own private chunk.
So if you have 10 keybindes and now added another, well, you would of had your variable be a list anyways, so just check the list size and then parse the variables as normal.
Whats more interesting is if you add a whole new data variable into the mix. You can just add a new subchunk that holds that variable.
I think FBX goes further by actually storing what the variable is (int, float, string, etc…) so that you dont need to even know what the variable is before hand.
Also, since we are storing the chunk size as a UInt32, the max file size would be 4,294,967,295 bytes, which would be 4.2 gigabytes.
I haven’t been doing this a long time, and this is probably not the most efficient, but it seems to be the easiest for me to keep under control.
I just always assume any data loaded from disk is always broken in some manner. I like to create an object with all defaults (strings all initialized with “”, ints all initialized with some default value, and I generally use lists instead of arrays so there’s less issues with sizing not being exactly correct) and then call a PopulateFromDisk method that takes the data pulled from disk and populates the object. Any variable that wasn’t assigned a value from the data pulled from disk isn’t null, it is just whatever the default was when I created the object.
You can still run into weird behavior with missing data doing it this way, but not a whole lot of nullreference exception errors. Obviously though it is best to anticipate and test what adding that 11th keybinding will do when only 10 are saved on disk.
I like to handle this by creating an object with a character’s info that I then reference from the character’s gameobject. So when I load a saved character from disk I go like this:
Create an instance of a Character object, which is not a monobehavior or GameObject, just a regular C# class, mostly with just a bunch of public values, lists, etc, to be accessed by monobehavior scripts later
Populate all the values in the Character object from whatever I read from disk (from JSON, XML, CSV, even SQL DB, doesn’t really matter how it is stored)
Instantiate my player’s GameObject
Tell a script on the player GameObject to look at the Character object for all its info
That way whenever I need any information about the character I can just look at the Character object, even if I’m not instantiating the player gameobject. This can be helpful for login screens where you need to know everything about a character, but don’t want any associated gameobjects. It also makes it easy to dump all the character info back to disk, since it is all stored in the Character class, not spread out across a bunch of monobehavior scripts attached to the player gameobject.
OK so what I did is basically created a IVariable ~wrapper it can… For File
-WriteToDisk
-ReadFromDisk
-ReadFromDiskNull //it calls this if it can’t find the data it’s looking for
For Networking
-WriteNetworkConstructor //for initial values… i.e. when a new client connects it gets everything
-ReadNetworkConstructor
-bool isDirty
-WriteNetworkDirty //for runtime changes
-ReadNetworkDirty
Then I have 2 lists
-ListVarFile read/write (only the server deals with this)
-ListVarNetwork read/write
The reason I separate the two is because things like string heroName is both written to file, and to clients. But transform.position is only networked… not saved to file. In otherwords everything saved to file is also networked, but not everything networked is saved to file.
So in the hero data file for example it attempts to find the string heroName using ReadFromDisk. If it can’t find it then it sets the string to “” by ReadFromDiskNull. When attempting to load Inventory if it can’t find it then it adds basic starter items (i.e. for a new hero). When a new player connects the hero name is sent to the client using WriteNetworkConstructor. If at any point there hero name is changed, it flags it as dirty, and the next network package sends the hero name to clients using WriteNetworkDirty. Then when saving the hero file it uses WriteToDisk.
WriteNetworkConstructor and WriteNetworkDirty are the same thing for fields like int or string. But they are different for complicated variables such as a Inventory. For Inventory sending WriteNetworkConstructor is called it writes full… all items in the list. When WriteNetworkDirty is called it only sends things that changed (i.e. Add/Remove/Set). And then within each item only the variables that changed using a dirty mask (i.e. slot).
Seems to work OK so far. Some things are tricky to handle such as trying to lump different types of data together -fields such as int/string
-reference types such as classes,
-containers such as dictionaries or lists
-things without constructors such as Monobehaviours. Although it may be best to scrap Monobehaviours containing data and pack it all in a constructable Class as @Joe-Censored pointed out.
Writing to file uses a nested dictionary hash system to identify what it’s looking for version safety. Writing to network doesn’t use any identification or hashes because server/client must have the same version and no safety checks are needed.
Right now for runtime network data containers I have 2 types.
1: Fixed lists that use a 1bit dirtyMask
2: Variable length list that uses a dictionary system (i.e. for item inventory… so things can be added/removed/or set).
All network data is sent using UNET MessageBase.
Thanks for the help. I tried this like 20 different ways before I got to this point…