Menu
CoddyTech

Food

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

Food lies on a random cell. Cells are whole numbers, so pick x and z with the int version of Random.Range. With ints the maximum is left out: Random.Range(1, 7) rolls a die, 1 to 6, never 7. To include a number, ask for one more than it.

With float arguments Random.Range returns any number in between, such as 3.62, which is not the middle of a cell, so the snake would never meet the food. A chest on a 10 by 10 grid with cells 0 to 9:

int row = Random.Range(0, 10);      // 0 to 9
int column = Random.Range(0, 10);
chest.position = new Vector3(column, 0f, row);

The board holds one food at a time, so the game makes it once, in Start(), and moves it whenever it needs a new place. GameManager owns the food, and it reads the board's size from the snake's edge through a snake field.

challenge icon

Challenge

Medium

Fill in GameManager. The scene sets its snake to the head's Snake and its foodPrefab to a red sphere.

  1. Add public Snake snake;, public GameObject foodPrefab; and private Transform food;.
  2. In Start(), instantiate foodPrefab, keep its Transform in food, and call MoveFood().
  3. Write void MoveFood(): it puts food on a random cell, x and z each from -snake.edge to snake.edge, and y 0.

Press Play and find the food on the board, then press Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    // Runs the game: the food, the score and the game over. Chapter 2 fills it in.
}
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