Create a Save/Load sytem in unity using C# and JSON data

In this tutorial I will show how I made a save and load system in unity using JSON data.

Before starting I need to tell something . That is , I am clearly saying the structure and code you will see here are not the best. I mean there are other better ways to code this thing . I just wanted to make it easy to understand for beginner. I used simple clear things so that beginners can focus on the basic idea. Okay lets get started.

Lets start by pointing out what things we will be doing..

  • Make the basic UI for the system (Texts and buttons)
  • Create a PlayerData script where we will have all the data we want to save and load
  • Create a GameState script to track and modify data
  • Create a SaveLoadJSON script to save and load the data
  • Attach Game state and SaveLoadJSON script with the GameObject “GamePanel”.
  • Drag the Text fields and the other necessary item in place for both the scripts.
  • Assign proper method in proper buttons OnClick event for increasing and decreasing the values
  • Add proper method in the save buttons OnClick event

Making Basic UI

No fancy things. I just added the UI elements in a structured way formyself to understand easily. The final Hierarchy will look like this.

PlayerData.cs

using UnityEngine;

[System.Serializable]
public class PlayerData
{
    public int health;
    public int gold;
    public Vector2 position;
}

GameState.cs

using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.Serialization;

public class GameState : MonoBehaviour
{
    [SerializeField] private int currentHealth;
    [SerializeField] private int currentGold;
    [SerializeField] private Vector2 currentPosition;

    [SerializeField] private SaveLoadJSON saveLoadJson;

    [Header("UI Items")]
    [SerializeField] private TextMeshProUGUI healthText;
    [SerializeField] private TextMeshProUGUI goldText;
    [SerializeField] private TextMeshProUGUI positionText;


    private void Start()
    {
        saveLoadJson.LoadGame();
    }


    public int GetCurrentHealth()
    {
        return currentHealth;
    }

    public int GetCurrentGold()
    {
        return currentGold;
    }

    public Vector2 GetCurrentPosition()
    {
        return currentPosition;
    }

    public void SetCurrentHealth(int health)
    {
        currentHealth = health;
        healthText.text = ("Health : "+ currentHealth);
    }

    public void SetCurrentGold(int gold)
    {
        currentGold = gold;
        goldText.text = ("Gold : "+ currentGold);
    }

    public void SetCurrentPosition(Vector2 position)
    {
        currentPosition.x = position.x;
        currentPosition.y = position.y;
        positionText.text = ("Player position : \n"+ "(x,y) = ("+currentPosition.x+","+currentPosition.y+")");

    }

    public void ModifyHealth(int value)
    {
        SetCurrentHealth(currentHealth+value);
    }

    public void ModifyGOld(int value)
    {
        SetCurrentGold(currentGold+value);
    }

    public void ModifyXPosition(int a)
    {
        SetCurrentPosition(new Vector2(currentPosition.x+a,currentPosition.y));
    }
    public void ModifyYPosition(int a)
    {
        SetCurrentPosition(new Vector2(currentPosition.x,currentPosition.y+a));
    }
}

SaveLoadJSON.cs

using System.IO;
using UnityEngine;
using UnityEngine.Serialization;

public class SaveLoadJSON : MonoBehaviour
{
    string saveFilePath;
    private PlayerData playerData;
    [SerializeField] private GameState gameState;

    void Awake()
    {
        playerData = new PlayerData();
        saveFilePath = Application.persistentDataPath + "/PlayerData.json";
    }

    public void SaveGame()
    {
        GetCurrentData();
        string savePlayerData = JsonUtility.ToJson(playerData);
        File.WriteAllText(saveFilePath, savePlayerData);

        Debug.Log("Save file created at: " + saveFilePath);
    }

    public void LoadGame()
    {
        if (File.Exists(saveFilePath))
        {
            string loadPlayerData = File.ReadAllText(saveFilePath);
            playerData = JsonUtility.FromJson<PlayerData>(loadPlayerData);
            gameState.SetCurrentHealth(playerData.health);
            gameState.SetCurrentGold(playerData.gold);
            gameState.SetCurrentPosition(playerData.position);
        }
        else
        {
            Debug.Log("There is no save files to load!");
            gameState.SetCurrentHealth(100);
            gameState.SetCurrentGold(0);
            gameState.SetCurrentPosition(Vector2.zero);
            SaveGame();
            LoadGame();
        }
    }

    private void GetCurrentData()
    {
        playerData.health = gameState.GetCurrentHealth();
        playerData.gold = gameState.GetCurrentGold();
        playerData.position = gameState.GetCurrentPosition();
    }
}

Attaching scripts with GameObject and assigning proper things

Adding OnClick events

There are buttons for increasing and decreasing values of Health, golds and positions.

We will have to add proper OnClick events from the GameState script. For increasing we will put value 1 and for decreasing we will put value -1.

And in the save buttons on click event we will use the SaveData method from the SaveLoadJSON script.

You are all set.. When we start the game if we have any saved data then it will be loaded and if not then a default value will be saved and get loaded. And if we already have any saved data then it will get loaded. We can change the values of health , gold and position. After changing we will have to press the save button to save the data for future…

That’s it. If you don’t understand anything then please leave a comment. If you need the source code then also leave a comment. Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Index