Menu
CoddyTech

保存风力

本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 26 课,共 64 课。

每次启动时,构建版本都会按构建时的状态加载每个资源,因此玩家的风会恢复为 2。PlayerPrefs 会保存它,而 Start 会将它写回资源。

challenge icon

挑战

简单

为下一局保留玩家的风力。

  1. 在 WindVane 中,每次箭头键改变风力时,调用 PlayerPrefs.SetFloat("Wind", wind.strength);。
  2. 在 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 在线编辑器