保存风力
本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 26 课,共 64 课。
每次启动时,构建版本都会按构建时的状态加载每个资源,因此玩家的风会恢复为 2。PlayerPrefs 会保存它,而 Start 会将它写回资源。
挑战
简单为下一局保留玩家的风力。
- 在
WindVane中,每次箭头键改变风力时,调用PlayerPrefs.SetFloat("Wind", wind.strength);。 - 在
Start中,在Show()之前,如果PlayerPrefs.HasKey("Wind"),就将wind.strength设为PlayerPrefs.GetFloat("Wind")。新玩家会保留资源中的 2。
按“开始”,改变风力,然后按“停止”再按“开始”:风力保持不变。然后按“检查”。
亲手试试
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;
}
}
Unity 游戏架构中的所有课
自己练习: Unity 在线编辑器