Menu
CoddyTech

Save the Wind

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

A build loads every asset as it was built each time it starts, so the player's wind would be back at 2. PlayerPrefs keeps it, and Start writes it back into the asset.

challenge icon

Challenge

Easy

Keep the player's wind for the next game.

  1. In WindVane, each time an arrow changes the wind, call PlayerPrefs.SetFloat("Wind", wind.strength);.
  2. In Start, before Show(), if PlayerPrefs.HasKey("Wind"), set wind.strength to PlayerPrefs.GetFloat("Wind"). A new player keeps the asset's 2.

Press Play, change the wind, Stop and Play: the wind is the same. Then Check.

Try it yourself

using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class WindVane : MonoBehaviour
{
    public TMP_Text windText;
    public WindSettings wind;

    void Start()
    {
        Show();
    }

    void Update()
    {
        if (Keyboard.current.upArrowKey.wasPressedThisFrame)
        {
            wind.strength = Mathf.Min(wind.strength + 1f, 5f);
            Show();
        }
        if (Keyboard.current.downArrowKey.wasPressedThisFrame)
        {
            wind.strength = Mathf.Max(wind.strength - 1f, 0f);
            Show();
        }
    }

    void Show()
    {
        windText.text = "Wind: " + wind.strength;
    }
}

All lessons in Game Architecture in Unity

Practice on your own: Unity playground