Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning C# by Developing Games with Unity - Seventh Edition

You're reading from  Learning C# by Developing Games with Unity - Seventh Edition

Product type Book
Published in Nov 2022
Publisher Packt
ISBN-13 9781837636877
Pages 466 pages
Edition 7th Edition
Languages
Author (1):
Harrison Ferrone Harrison Ferrone
Profile icon Harrison Ferrone

Table of Contents (18) Chapters

Preface 1. Getting to Know Your Environment 2. The Building Blocks of Programming 3. Diving into Variables, Types, and Methods 4. Control Flow and Collection Types 5. Working with Classes, Structs, and OOP 6. Getting Your Hands Dirty with Unity 7. Movement, Camera Controls, and Collisions 8. Scripting Game Mechanics 9. Basic AI and Enemy Behavior 10. Revisiting Types, Methods, and Classes 11. Specialized Collection Types and LINQ 12. Saving, Loading, and Serializing Data 13. Exploring Generics, Delegates, and Beyond 14. The Journey Continues 15. Pop Quiz Answers
16. Other Books You May Enjoy
17. Index

Saving, Loading, and Serializing Data

Every game you’ve ever played works with data, whether it’s your player stats, game progress, or online multiplayer scoreboards. Your favorite game also manages internal data, meaning the programmers used hardcoded information to build levels, keep track of enemy stats, and write helpful utilities. In other words, data is everywhere.

In this chapter, we’re going to start with how both C# and Unity handle the filesystem on your computer, and move on to reading, writing, and serializing our game data. Our focus is on working with the three most common data formats you’ll likely come across: text files, XML, and JSON.

By the end of this chapter, you’ll have a foundational understanding of your computer’s filesystem, data formats, and basic read-write functionality. This will be the foundation you build your game data on, creating a more enriching and engaging experience for your players. You’...

Introducing data formats

Data can take different forms in programming, but the three formats you should be familiar with at the beginning of your data journey are:

  • Text, which is what you’re reading right now
  • XML (Extensible Markup Language), which is a way of encoding document information so it’s readable for you and a computer
  • JSON (JavaScript Object Notation), which is a human-readable text format made up of attribute-value pairs and arrays

Each of these data formats has its own strengths and drawbacks, as well as applications in programming. For instance, text is generally used to store simpler, non-hierarchical, or nested information. XML is better at storing information in a document format, while JSON has a more diverse range of capabilities, specifically with database information and server communication with applications.

You can find more information about XML at https://www.xml.com and JSON at https://www.json.org...

Understanding the filesystem

When we say filesystem, we’re talking about something you’re already familiar with – how files and folders are created, organized, and stored on your computer. When you create a new folder on your computer, you can name it and put files or other folders inside it. It’s also represented by an icon, which is both a visual cue and a way to drag, drop, and move it anywhere you like.

Everything you can do on your desktop you can do in code. All you need is the name of the folder, or directory as it’s called, and a location to store it. Anytime you want to add a file or subfolder, you reference the parent directory and add your new content.

To drive the filesystem home, let’s start building out the DataManager class we created and attached to the Game Manager object in the Hierarchy in Chapter 10, Revisiting Types, Methods, and Classes:

  1. Open the DataManager script and update it with the following code...

Working with streams

So far, we’ve been letting the File class do all of the heavy lifting with our data. What we haven’t talked about is how the File class, or any other class that deals with reading and writing data, does that work under the hood.

For computers, data is made up of bytes. Think of bytes as the computer’s atoms; they make up everything—there’s even a C# byte type. When we read, write, or update a file, our data is converted into an array of bytes, which are then streamed to or from the file using a Stream object. The data stream is responsible for carrying the data as a sequence of bytes to or from a file, acting as a translator or intermediary for us between our game application and the data files themselves.

Figure 12.11: Diagram of streaming data to a file

The File class uses Stream objects for us automatically, and there are different Stream subclasses for different functionality:

  • Use a FileStream...

Serializing data

When we talk about serializing and deserializing data, what we’re really talking about is translation. While we’ve been translating our text and XML piecemeal in previous sections, being able to take an entire object and translate it in one shot is a great tool to have.

By definition:

  • The act of serializing an object translates the object’s entire state into another format
  • The act of deserializing is the reverse, taking the data from a file and restoring it to its former object state

Figure 12.17: Example of serializing an object into XML and JSON

Let’s take a practical example from the above image—an instance of our Weapon class. Each weapon has its own name and damage properties and associated values, which is called its state. The state of an object is unique, which allows the program to tell them apart.

An object’s state also includes properties or fields that are reference types...

Data roundup

Every individual module and topic we’ve covered in this chapter can be used by itself or combined to suit your project’s needs. For example, you could use text files to store character dialog and only load it when you need to. This would be more efficient than having the game keep track of it every time it runs, even when the information isn’t being used.

You could also put character data or enemy statistics into either an XML or JSON file and read from the file anytime you need to level up a character or spawn a new monster. Finally, you could fetch data from a third-party database and serialize it into your own custom classes. This is a super common scenario with storing player accounts and external game data.

You can find a list of data types that can be serialized in C# at: https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/types-supported-by-the-data-contract-serializer. Unity handles serialization a little differently...

Summary

And that’s a wrap on the basics of working with data! Congratulations on making it through this monster chapter intact. Data in any programming context is a big topic, so take everything you’ve learned in this chapter as a jumping-off point.

You already know how to navigate the filesystem and create, read, update, and delete files. You also learned how to effectively work with text, XML, and JSON data formats, as well as data streams. And you know how to take an entire object’s state and serialize or deserialize it into both XML and JSON. All in all, learning these skills was no small feat. Don’t forget to review and revisit this chapter more than once; there’s a lot here that might not become second nature on the first run-through.

In the next chapter, we’ll discuss the basics of generic programming, get a little hands-on experience with delegates and events, and wrap up with an overview of exception handling.

Pop quiz—data management

  1. Which namespace gives you access to the Path and Directory classes?
  2. In Unity, what folder path do you use to save data between runs of your game?
  3. What data type do Stream objects use to read and write information to files?
  4. What happens when you serialize an object into JSON?

Don’t forget to check your answers against mine in the Pop Quiz Answers appendix to see how you did!

Join us on discord!

Read this book alongside other users, Unity game development experts and the author himself.

Ask questions, provide solutions to other readers, chat with the author via. Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/csharpwithunity

lock icon The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity - Seventh Edition
Published in: Nov 2022 Publisher: Packt ISBN-13: 9781837636877
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}