Menu
CoddyTech

Recap: Save Slots

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

challenge icon

Challenge

Medium

Fill the save slots; PathFor(i) and Show() are ready.

  1. In SlotSave, start a farm at day = 1 and gold = 20.
  2. In Start(), load each slot whose file exists into slots[i].
  3. Space puts a new SlotSave() in an empty selected slot, or plays a day: day +1, gold +15. Save it, then Show().

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

Practice on your own: Unity playground