Recap: Save Slots
Part of the Game Architecture in Unity section of Coddy's Unity journey. Lesson 33 of 64.
Challenge
MediumFill the save slots; PathFor(i) and Show() are ready.
- In
SlotSave, start a farm atday = 1andgold = 20. - In
Start(), load each slot whose file exists intoslots[i]. - Space puts a
new SlotSave()in an empty selected slot, or plays a day:day+1,gold+15. Save it, thenShow().
Press Play and Space: > Slot 1: Day 1, 20 gold. 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()
{
// Load every slot that has a file
Show();
}
void Update()
{
// Space: start a farm in the selected slot, or play a day there, then save it
}
// 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;
}
}
}
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