Menu
CoddyTech

共享设置

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

难度设置会同时改变所有敌人,因此适合放在一个所有敌人都引用的资源中。每一帧,敌人都会读取资源中的速度,而菜单的 Hard 按钮会写入同一个资源:

[CreateAssetMenu(menuName = "Game/Difficulty")]
public class Difficulty : ScriptableObject
{
    public float enemySpeed = 2f;
}
public class Enemy : MonoBehaviour
{
    public Difficulty difficulty;
    public Transform player;

    void Update()
    {
        float step = difficulty.enemySpeed * Time.deltaTime;
        transform.position = Vector3.MoveTowards(transform.position, player.position, step);
    }
}
// DifficultyMenu.cs,已连接到 Hard 按钮的 onClick
public Difficulty difficulty;

public void SetHard()
{
    difficulty.enemySpeed = 4f;
}

敌人的字段和菜单的字段都引用同一个资源,因此调用 SetHard() 后,每个敌人在下一次 Update 时都会读取 4。之后从预制件生成的敌人也一样,只要它的字段中引用了这个资源。这是因为敌人移动时会读取 difficulty.enemySpeed。如果敌人在 Start 中将它复制到自己的字段,之后就会一直以 2 的速度移动。

游戏运行期间所做的更改会保存在哪里,取决于游戏运行的位置。每次启动时,构建版本都会加载构建时的资源,因此玩家选择 Hard 后,这个设置不会保留到下一局。要保留玩家的选择,请使用 PlayerPrefs 保存,并在游戏启动时将其写回资源。在 Editor 中,游戏更改的是项目中的资源。按下 Stop 后,这项更改仍会保留;而场景中的对象会恢复到 Inspector 中的值。下一次点击“开始”时,游戏会以 Hard 难度启动,资源中的值也会一直保持为 4,直到你将其改回去。

challenge icon

挑战

中等

通过共享一个资源,让箭头改变每艘船的风力。

  1. 在 Sailboat 中,将 windStrength 替换为 public WindSettings wind;,并使用 wind.strength 航行。
  2. 在 WindVane 中,将 strength 替换为 public WindSettings wind;。
  3. 让箭头改变 wind.strength(0 到 5),并让文本显示风力,例如 Wind: 3。

按下“开始”,然后按向上键:三艘船都会加速。然后按“检查”。

亲手试试

using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class WindVane : MonoBehaviour
{
    public TMP_Text windText;
    public float strength = 2f;

    void Start()
    {
        Show();
    }

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

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

Unity 游戏架构中的所有课

自己练习: Unity 在线编辑器