打造属于你的版本
Coddy Unity 3D 贪吃蛇游戏 课程的第 14 课,共 14 课。
还差一个功能:关闭游戏后仍会保留的最高分。PlayerPrefs可以保存它:在Start()中读取,并在游戏结束且分数超过最高分时保存。赛车游戏的最佳圈速则相反,因为时间越短越好:
if (lapTime < bestLap)
{
bestLap = lapTime;
PlayerPrefs.SetFloat("BestLap", bestLap);
}接下来,你可以自行调整游戏。Snake中的数值决定了游戏的感觉:tick设为 0.25,开局会比较平缓;设为 0.1,开局则会比较快。speedUp设为 0.01,会让蛇更早加速;minTick设为 0.05,则会让游戏后期变得紧张刺激。这个玩家的 Inspector 是只读的,而且课程场景会将这三个字段设为代码中的值,因此请在它们声明的位置修改数值,然后按下 Play。在你自己的 Unity 项目中,请在 Inspector 的 Snake 组件上修改这些数值:只在代码中设置新的默认值,不会影响场景中已有的组件。
挑战
困难让最高分在不同局次间保留,然后调整游戏。
- 在
GameManager中,添加public TMP_Text bestText;和private int best; - 在
Start()中,使用best = PlayerPrefs.GetInt("BestScore", 0);,并显示"Best: " + best。 - 在
GameOver()中,当分数超过最高分时,设置最高分,将其保存为BestScore,并显示出来。 - 调整 Snake 中声明的
tick、speedUp和minTick。
按下“开始”,创造一个最高分,然后再玩一次:最高分会保留在右上角。然后按“检查”。
亲手试试
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Snake snake;
public GameObject foodPrefab;
public TMP_Text scoreText;
public GameObject gameOverPanel;
public Button playAgainButton;
private Transform food;
private int score;
void Awake()
{
Instance = this;
}
void Start()
{
scoreText.text = "Score: 0";
playAgainButton.onClick.AddListener(PlayAgain);
food = Instantiate(foodPrefab).transform;
MoveFood();
}
public bool IsFood(Vector3 cell)
{
return cell == food.position;
}
public void Eat()
{
score++;
scoreText.text = "Score: " + score;
MoveFood();
}
public void GameOver()
{
gameOverPanel.SetActive(true);
}
void PlayAgain()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
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 在线编辑器