Menu
CoddyTech

Pick and Delete a Slot

Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 34 of 64.

This chapter wrote saves as JSON: a [System.Serializable] save class, files in Application.persistentDataPath, and field initializers that fill in what an old save lacks. The slot menu now gets its last two controls.

challenge icon

Challenge

Medium

Let the player pick a slot and delete it.

  1. In Update(), the down arrow adds 1 to selected and the up arrow takes 1 off, kept from 0 to 2 with Mathf.Min and Mathf.Max. Then Show().
  2. DeleteSelected() deletes the selected slot's file with File.Delete, sets the slot to null and calls Show().

Press Play, fill slot 3 and click Delete: it reads empty. Then Check.

Try it yourself

using System.IO;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class SlotMenu : MonoBehaviour
{
    public TMP_Text[] slotTexts;
    private SlotSave[] slots = new SlotSave[3];
    private int selected;

    void Start()
    {
        for (int i = 0; i < slots.Length; i++)
        {
            if (File.Exists(PathFor(i)))
            {
                slots[i] = JsonUtility.FromJson<SlotSave>(File.ReadAllText(PathFor(i)));
            }
        }
        Show();
    }

    void Update()
    {
        // The arrows pick a slot
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            if (slots[selected] == null)
            {
                slots[selected] = new SlotSave();
            }
            else
            {
                slots[selected].day++;
                slots[selected].gold += 15;
            }
            File.WriteAllText(PathFor(selected), JsonUtility.ToJson(slots[selected]));
            Show();
        }
    }

    // The Delete button calls this
    public void DeleteSelected()
    {
    }

    string PathFor(int index)
    {
        return Path.Combine(Application.persistentDataPath, "slot" + (index + 1) + ".json");
    }

    void Show()
    {
        for (int i = 0; i < slots.Length; i++)
        {
            string line = "Slot " + (i + 1) + ": ";
            if (slots[i] == null)
            {
                line += "empty";
            }
            else
            {
                line += "Day " + slots[i].day + ", " + slots[i].gold + " gold";
            }
            if (i == selected)
            {
                line = "> " + line;
            }
            slotTexts[i].text = line;
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Game Architecture in Unity

Practice on your own: Unity playground