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. To include a number, ask for one more than it. With floats it returns numbers such as 3.62, not the middle of a cell.

On a board with edge 4, the columns run from -4 to 4:

int x = Random.Range(-4, 5);   // -4 to 4

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 reads the board's size from the snake's edge through its snake field.

challenge icon

Challenge

Medium

Put the food on a random cell of the board.

  1. In GameManager, add public Snake snake;, public GameObject foodPrefab; and private Transform food; (the scene links the first two).
  2. In Start(), food = Instantiate(foodPrefab).transform;, then call MoveFood().
  3. void MoveFood(): put food at a random x and z, each from -snake.edge to snake.edge, y 0.

Press Play: a red sphere lies on a cell, somewhere new each time. Then 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.
}

All lessons in Unity Game: Snake 3D

Practice on your own: Unity playground