Menu
CoddyTech

天降方块

本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 76 课,共 85 课。

challenge icon

挑战

中等

每秒在空中生成一个方块。保持操控功能不变。

  1. 添加 [SerializeField] private GameObject blockPrefab;、[SerializeField] private float spawnEvery = 1f; 和 private List<GameObject> blocks = new List<GameObject>();。
  2. 将 Time.deltaTime 加到 float timer 上;当它达到 spawnEvery 时,从中减去 spawnEvery。
  3. 然后在 new Vector3(Random.Range(-laneEdge, laneEdge), 10f, 0f) 处生成一个方块,并将它添加到 blocks 中。

按“运行”:方块会出现在跑道上方的高处。然后按“检查”。

亲手试试

using UnityEngine;

public class Runner : MonoBehaviour
{
    [SerializeField] private float speed = 6f;
    [SerializeField] private float laneEdge = 4f;

    void Update()
    {
        Vector3 p = transform.position;
        p.x += Input.GetAxisRaw("Horizontal") * speed * Time.deltaTime;
        p.x = Mathf.Clamp(p.x, -laneEdge, laneEdge);
        transform.position = p;
    }
}

Unity 脚本基础中的所有课

自己练习: Unity 在线编辑器