Menu
CoddyTech

从文本加载关卡

Coddy Unity 游戏:打砖块 课程的第 11 课,共 19 课。

有多个关卡的游戏需要一种记录关卡的方式。文本是最简单的方式:每块砖用一个字符表示,每行用一个字符串表示。这里,数字表示需要击打对应次数的砖块,点表示空隙,而一个关卡的各行放在同一个字符串中,并用 / 分隔,因此场景的 levels 包含三种布局,第一个就是今天的墙。

string[] rows = "1.1/22".Split('/');   // "1.1" 和 "22"
char c = rows[1][0];                     // '2'

数字字符不是它所表示的数字:'3' 是一个字符,其编码是 51。数字字符的编码按顺序排列,因此减去 '0' 就能得到对应的数字:'3' - '0' 是 int 3。每一行都根据自身长度居中,-(line.Length - 1) * spacingX / 2f。

challenge icon

挑战

中等

根据文本构建墙,例如 3.3.3/22222。

  1. 在 GameManager 中,移除 rows、columns 和 rowHits;添加 public string[] levels; 和 int level;
  2. 将 BuildWall() 替换为 BuildLevel(int index):将 index 存入 level,在 '/' 处分割 levels[index],并为每个数字 c 构建一个居中的砖块,调用 SetHits(c - '0');点号表示空位。
  3. Start() 调用 BuildLevel(0)。

按“开始”:现在,墙的构建方式相同,但使用的是第一关的文本。然后点击“检查”。

亲手试试

using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Brick brickPrefab;
    public Transform wall;
    public int rows = 5;
    public int columns = 9;
    public float spacingX = 1.75f;
    public float spacingY = 0.75f;
    public float topY = 6f;
    public int[] rowHits = { 2, 1, 1, 1, 1 };
    public int lives = 3;
    public TMP_Text scoreText;
    public TMP_Text livesText;

    int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        BuildWall();
        ShowHud();
    }

    void BuildWall()
    {
        float left = -(columns - 1) * spacingX / 2f;
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < columns; col++)
            {
                Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
                Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
                brick.SetHits(rowHits[row]);
            }
        }
    }

    public void BrickBroken(Brick brick)
    {
        score += brick.points;
        ShowHud();
    }

    public void BallLost(Ball lost)
    {
        lives--;
        ShowHud();
        lost.ResetToPaddle();
    }

    void ShowHud()
    {
        scoreText.text = "Score: " + score;
        livesText.text = "Lives: " + lives;
    }
}

Unity 游戏:打砖块中的所有课

自己练习: Unity 在线编辑器