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
MediumLet the player pick a slot and delete it.
- In
Update(), the down arrow adds 1 toselectedand the up arrow takes 1 off, kept from 0 to 2 withMathf.MinandMathf.Max. ThenShow(). DeleteSelected()deletes the selected slot's file withFile.Delete, sets the slot tonulland callsShow().
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;
}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Game Architecture in Unity
1Components, Not Hierarchies
Small ComponentsA Base Enemy ScriptAbstract ComponentsComponents Working TogetherRecap: Modular TurretRecap: Twin Cannon4Serialized Data
Serializable ClassesLists in the InspectorEnums in the InspectorRecap: Loot TableRecap: Roll the Loot2Interfaces in Unity
IDamageableInterfaces and TryGetComponentGetComponentsRecap: Interact KeyRecap: Nearest in ReachPractice on your own: Unity playground