Menu
CoddyTech

Eat

Lesson 6 of 14 in Coddy's Unity Game: Snake 3D course.

The snake eats when its head steps onto the food's cell. Both stand on whole numbers, so comparing their positions with == is safe: Unity's == on Vector3 counts two positions as equal when they are closer than 0.00001, and adding whole cells never leaves a gap that small.

The snake knows when it steps; the GameManager knows where the food is and keeps the score. So after each step the snake asks, and the GameManager answers: IsFood(cell) returns a bool, and Eat() adds a point and moves the food. The snake reaches the GameManager through a static Instance, the singleton you met in the C# for Unity journey.

Ask about the cell the head has entered, after the move. A key on a grid is picked up the same way:

transform.position = next;
if (key.position == transform.position)
{
    keysHeld++;
    key.gameObject.SetActive(false);
}
challenge icon

Challenge

Medium

In GameManager:

  1. Add public static GameManager Instance;, set it in Awake(), and add private int score;.
  2. Write public bool IsFood(Vector3 cell): true when cell is the food's position.
  3. Write public void Eat(): add 1 to score and call MoveFood().

In Snake, at the end of Step(), after the head has moved: if the head's cell is food, call Eat().

Press Play and steer onto the food, then press Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public Snake snake;
    public GameObject foodPrefab;
    private Transform food;

    void Start()
    {
        food = Instantiate(foodPrefab).transform;
        MoveFood();
    }

    void MoveFood()
    {
        int x = Random.Range(-snake.edge, snake.edge + 1);
        int z = Random.Range(-snake.edge, snake.edge + 1);
        food.position = new Vector3(x, 0f, z);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Snake 3D