得分
Coddy Unity 3D 贪吃蛇游戏 课程的第 11 课,共 14 课。
分数会在 GameManager 中不断增加,但没人看得到。左上角的 TextMeshPro 文本会显示分数:在 Inspector 中设置一个 TMP_Text 字段,然后在代码中写入它的 text。
每次数字变化后,都在同一个位置写入文本。这样,屏幕上的分数就不会落后。商店也会用同样的方式更新金币:
public void Buy(int price)
{
coins -= price;
coinsText.text = "Coins: " + coins;
}也要在 Start() 中设置一次文本,这样第一帧就会显示实际分数,无论场景中的文本是什么。
挑战
中等在屏幕上显示分数。
- 在
GameManager中,添加using TMPro;和public TMP_Text scoreText;(场景会关联 ScoreText)。 - 在
Start()中,显示Score: 0。 - 在
Eat()中,得分增加后,显示"Score: " + score。
按“开始”并吃掉食物:左上角的分数会显示 Score: 1、Score: 2。然后点击“检查”。
亲手试试
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Snake snake;
public GameObject foodPrefab;
private Transform food;
private int score;
void Awake()
{
Instance = this;
}
void Start()
{
food = Instantiate(foodPrefab).transform;
MoveFood();
}
public bool IsFood(Vector3 cell)
{
return cell == food.position;
}
public void Eat()
{
score++;
MoveFood();
}
void MoveFood()
{
List<Vector3> free = new List<Vector3>();
for (int x = -snake.edge; x <= snake.edge; x++)
{
for (int z = -snake.edge; z <= snake.edge; z++)
{
Vector3 cell = new Vector3(x, 0f, z);
if (!snake.Occupies(cell))
{
free.Add(cell);
}
}
}
food.position = free[Random.Range(0, free.Count)];
}
}
Unity 3D 贪吃蛇游戏中的所有课
自己练习: Unity 在线编辑器