Menu
CoddyTech

自分らしく仕上げよう

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は読み取り専用で、コースのシーンではこれら3つのフィールドにコード内の値が設定されているため、宣言されている場所で値を変更してからPlayを押してください。自分のUnityプロジェクトでは、InspectorでSnakeコンポーネントの値を変更してください。コード内でデフォルト値を変更しても、シーン内にすでにあるコンポーネントには反映されません。

challenge icon

チャレンジ

難しい
  1. GameManagerに、public TMP_Text bestText;(シーンで右上のBestTextに設定)とprivate int best;を追加します。
  2. Start()で、キーBestScoreからbestを読み込み、保存されていない場合は0にし、Best: 0として表示します。
  3. GameOver()で、scoreがbestを上回った場合、それをベストスコアにして、BestScoreのキーで保存し、表示します。

Playを押してから、Checkを押します。その後プレイして、ゲームが自分にとってちょうどよく感じられるまで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)];
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Unityゲーム:3Dスネークのすべてのレッスン