Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity Cookbook

You're reading from   Unity Cookbook Over 160 recipes to craft your own masterpiece in Unity 2023

Arrow left icon
Product type Paperback
Published in Nov 2023
Publisher Packt
ISBN-13 9781805123026
Length 780 pages
Edition 5th Edition
Languages
Tools
Arrow right icon
Authors (3):
Arrow left icon
Sinéad Murphy Sinéad Murphy
Author Profile Icon Sinéad Murphy
Sinéad Murphy
Matt Smith Matt Smith
Author Profile Icon Matt Smith
Matt Smith
Shaun Ferns Shaun Ferns
Author Profile Icon Shaun Ferns
Shaun Ferns
Arrow right icon
View More author details
Toc

Table of Contents (22) Chapters Close

Preface 1. Displaying Data with Core UI Elements 2. Responding to User Events for Interactive UIs FREE CHAPTER 3. Inventory and Advanced UIs 4. Playing and Manipulating Sounds 5. Textures, Materials, and 3D Objects 6. Creating 3D Environments with Terrains 7. Creating 3D Geometry with ProBuilder 8. 2D Animation and Physics 9. Animated Characters 10. Saving and Loading Data 11. Controlling and Choosing Positions 12. Navigation Meshes and Agents 13. Cameras, Lighting, and Visual Effects 14. Shader Graphs and Video Players 15. Particle Systems and Other Visual Effects 16. Mobile Games and Applications 17. Augmented Reality (AR) 18. Virtual and Extended Reality (VR/XR) 19. Advanced Topics – Gizmos, Automated Testing, and More 20. Other Books You May Enjoy
21. Index

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...
lock icon The rest of the chapter is locked
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 €18.99/month. Cancel anytime