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
EasyKeep the player's wind for the next game.
- In
WindVane, each time an arrow changes the wind, callPlayerPrefs.SetFloat("Wind", wind.strength);. - In
Start, beforeShow(), ifPlayerPrefs.HasKey("Wind"), setwind.strengthtoPlayerPrefs.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
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 Reach5ScriptableObjects
Data AssetsWeapon StatsShared SettingsSave the WindWaves as DataRecap: Item DatabaseRecap: Buy from the ShopPractice on your own: Unity playground