Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

Saving and Loading Data

Times when we wish to load data include retrieving high scores from previous plays of a game, or perhaps remembering data values between scenes. Another time to load data is when a level layout is stored in a data file (such as text characters, or a data format like XML or JSON), and when a scene begins, that data is loaded and used to dynamically create GameObjects for the scene. And of course, we must have saved the data previously in order to be able to load it at a later time.

Some of the saving/loading is ephemeral – just while a game is playing – and everything is reset the next time the game is run. Other times, data can be stored that is remembered between game plays, either as part of the build application’s private data, or to shared folders that can be changed from outside the application, as data on a web server, or via a web communication.

Sometimes, data to be saved are as simple as individual numbers or text strings...

Saving data between scenes using static properties

Keeping track of the player’s progress and user settings during a game is vital to give your game a greater feeling of depth and content. In this recipe, we will learn how to make our game remember the player’s score between the different levels (scenes).

Note that this example game is rigged! In this game, higher will always win, and lower will always lose, but we can build on this simple game to count, store, and retrieve the number of wins and games that have been played.

Figure 10.1: Our Higher or Lower game, with the score being remembered between scenes

Getting ready

We have included a complete project in a Unity package named game_HigherOrLower in the 10_01 folder. To follow this recipe, we will import this package as the starting point.

How to do it...

To save and load player data, follow these steps:

  1. Create a new Unity 2D project, and import the game_HigherOrLower package...

Saving data between scenes and games using PlayerPrefs

While the previous recipe illustrates how the static properties allow a game to remember values between different scenes, these values are forgotten once the game application is exited. Unity provides the PlayerPrefs feature to allow a game to store and retrieve data between the different game-playing sessions.

Getting ready

This recipe builds upon the previous recipe, so make a copy of that project and work from it.

How to do it...

To save and load the player data using PlayerPrefs, follow these steps:

  1. Delete the C# script PlayerData.
  2. Edit the C# script called UpdateScoreText by replacing the Start() method with the following code:
    void Start(){
       int scoreCorrect = PlayerPrefs.GetInt("scoreCorrect");
       int scoreIncorrect = PlayerPrefs.GetInt("scoreIncorrect");
       int totalAttempts = scoreCorrect + scoreIncorrect;
       string scoreMessage = "Score = ";
      ...

Reading data from a text file

Text files are used to store and communicate data for many purposes. Unity makes it easy for you to read in the contents of a text file via the built-in TextAsset script class. In this recipe, you’ll add a UI Text item to a scene, and then write a script that at runtime will read the contents from the text file and display them to the player.

Figure 10.4: Showing the text file contents on screen at runtime

Getting ready

You can use any text file as the data for this recipe. We’ve provided a small text file containing a list of cities, in a cities.txt file in the 10_03 folder.

Figure 10.5: Contents of the text file cities.txt

How to do it...

To read data from a text file, perform the following steps:

  1. Create a new Unity 2D project.
  2. Import the provided cities.txt text file into the project (or use some other text file you have on your computer).
  3. Load the TextMeshPro essentials resources...

Loading game data from a text file map

Rather than having to create and place every GameObject on the screen by hand for every level of a game, a better approach can be to create the text files of rows and columns of characters, where each character corresponds to the type of GameObject that is to be created in the corresponding location.

In this recipe, we’ll use a text file and a set of prefab sprites to display a graphical version of a text data file, for a screen from the classic game NetHack:

Figure 10.7: The level we’ve created from a text file level description

In the 10_04 folder, we have provided the following two files for this recipe:

  • level1.txt: A text file representing a level
  • absurd128.png: A 128 x 128 sprite sheet for NetHack

The level data came from the NetHack Wikipedia page, while the sprite sheet came from SourceForge:

Writing data to a file

Just as we may wish to read data from a file, there are times when it is useful to save data to a file. For example, we may want to save data from our game into our local computer, whether for debugging, recording game testing experiments, and so on.

In this recipe, we’ll declare a data structure for player’s names and scores, and save the data for a player as a JSON text file.

Figure 10.13: Player name and score data saved as a JSON text file

How to do it...

To write data to a file, perform the following steps:

  1. Create a new Unity 2D project.
  2. Create a new, empty folder in the Project panel, named Data. We’ll write our JSON text file into this folder.
  3. Create a new C# script class, PlayerScore, with the following code:
    using UnityEngine;
    using System;
    [Serializable]
    public class PlayerScore {
        public string name;
        public int score;
        public string ToJson() {
            bool prettyPrintJson...

Logging player actions and game events to a file

The comma separated values (CSV) text file format is a good format to save data in, since it is easily read into rows and columns by almost all spreadsheet applications.

In this recipe, we’ll write a script that offers a method that can be called from anywhere in our game, from any scene, which will add a row of text to a log file. The following is an example of the saved data when viewed in Microsoft Excel.

Figure 10.14: CSV log data viewed in a spreadsheet application

How to do it...

To log player actions and game events to a file, follow these steps:

  1. Create a new 2D project.
  2. Create a new AddToLogFile C# script class containing the following code:
    using UnityEngine;
    using System.IO;
    using System;
    using UnityEngine.SceneManagement;
    public class AddToLogFile : MonoBehaviour {
      private static string _fileName = "";
      private static string _folderName = "Logs";...

Reading data from the web

Much data and authentication is now available via web communications. In this recipe, we’ll create a simple Unity project using a C# script class to retrieve a small sample JSON text file from the web.

Figure 10.16: The JSON data downloaded from the web

Getting ready

The example of the web-published text file for this recipe can be found at the following URL (thanks to filesamples.com for publishing a range of test files on their website): https://filesamples.com/samples/code/json/sample1.json

However, you can replace this web address with any URL that returns a text file of some kind.

How to do it...

To read data from the web, perform the following steps:

  1. Create a new Unity 2D project.
  2. Load the TextMeshPro essentials resources, by choosing the menu Window | TextMeshPro | Import TMP Essential Resources.
  3. In the Hierarchy panel, add a Text TMP GameObject to the scene by choosing the menu GameObject...

Setting up a leaderboard using PHP and a database

Games are more fun when there is a leaderboard of high scores that the players have achieved. Even single-player games can communicate with a shared web-based leaderboard. This recipe creates the web server-side (PHP) scripts to set and get player scores from a SQL database. The recipe after this one then sees us creating a Unity game client that can communicate with this web leaderboard’s server.

Getting ready

This recipe assumes that you either have your own web hosting or are running a local web server. You could use the built-in PHP web server or a web server, such as Apache or Nginx. For the database, you could use a SQL database server such as MySQL or MariaDB. However, we’ve tried to keep things simple using SQLite – a file-based database system. So all you actually need on your computer is PHP 8, since it has a built-in web server and can talk to SQLite databases, which is the setup on which this...

Unity game communication with a web server leaderboard

In this recipe, we create a Unity game client that can communicate, via UI buttons, with our web server leaderboard from the previous recipe:

Figure 10.22: Screenshot showing a Unity game retrieving scores from a web server

Getting ready

Since this scene contains several UI elements and the code of the recipe is the communication with the PHP scripts and SQL database, in the 10_09 folder, we have provided a Unity package called UnityLeaderboardClient, containing a scene with everything set up for the Unity project.

How to do it...

To create a Unity game that communicates with the web server leaderboard, perform the following steps:

  1. Create a new 2D Unity project.
  2. Import the Unity package provided, UnityLeaderboardClient.
  3. Run the scene provided.
  4. Ensure that your PHP leaderboard is up and running.
  5. If you are not running locally (localhost:8000), you’ll need to update...

Further reading

The following are some useful resources to learn more about saving and loading data with Unity:

If you really want to get serious about game and web server security, then a proper API key strategy is probably the way to go. Here are some articles on sophisticated approaches to securing game data:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
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.
undefined
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 ₹800/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy