Building Snake Game in Unity: Step-by-Step Tutorial 2025 (2025)

  • Building Snake Game in Unity: Step-by-Step Tutorial 2025
  • What You'll Need
  • Setting Up Your Project
  • Creating the Game Scene
  • Setting Up the Camera
  • Creating the Game Borders
  • Designing the Snake
  • Creating the Snake Head
  • Creating the Snake Body
  • Scripting the Snake Movement
  • Growing the Snake
  • Creating the Food
  • Designing the Food
  • Scripting the Food Behavior
  • Handling Food Collision
  • Implementing Game Over Logic
  • Handling Border Collisions
  • Implementing the Game Over Method
  • Adding a Scoring System
  • Creating the Score UI
  • Polishing the Game
  • Adding Background Music
  • Adding Sound Effects
  • Adding a Game Over Screen
  • Conclusion
  • FAQ Section
  • Q: I'm getting an error when I try to run my game. What should I do?
  • Q: How can I make my snake move faster?
  • Q: How can I add more levels to my game?
  • Q: How can I add a pause menu to my game?
  • You Might Also Like:

Welcome, game enthusiasts! Today, we're diving into a classic—building the iconic Snake game in Unity. Whether you're a beginner or looking to brush up on your skills, this tutorial's got you covered. By the end, you'll have a fully functional Snake game and a solid understanding of Unity's fundamentals. So, let's get started!

What You'll Need

Before we dive in, make sure you have the following:

  • Unity Hub and Unity Editor (2024.1 or later)
  • Basic understanding of C#
  • A cup of coffee (optional but recommended)

Setting Up Your Project

Alright, let's set up our project. Open Unity Hub and create a new 2D project. I'm calling mine 'SnakeGame2025'—feel free to get creative with yours. Once your project's ready, you'll see the Unity Editor with its many panels. Don't worry, we'll go through them as we need 'em.

Creating the Game Scene

First things first, let's set up our game scene.

Setting Up the Camera

In the Hierarchy panel, you'll see the Main Camera. We want our game to have a top-down view. So, in the Inspector panel:

  • Set Transform Position to (0, 0, -10)
  • Set Orthographic Size to 10

This'll give us a nice view of our game area.

Creating the Game Borders

Next, let's create the game borders. In the Hierarchy, right-click and go to 2D Object > Sprites > Square. Rename it to 'Border' and in the Inspector, set the following:

  • Transform Position: (0, 5.5, 0)
  • Transform Scale: (10, 1, 1)

Duplicate this border three times and set their positions to (-5.5, 0), (5.5, 0), and (0, -5.5) respectively. This'll create a nice square play area.

Designing the Snake

Now for the star of the show—the snake! We'll create a simple snake using squares.

Creating the Snake Head

In the Hierarchy, right-click and go to 2D Object > Sprites > Square. Rename it to 'SnakeHead'. Let's give it a distinct color, say green. In the Inspector, find the Sprite Renderer component and change the Color to green.

Creating the Snake Body

Next, create another square for the body. Right-click on SnakeHead in the Hierarchy, go to 2D Object > Sprites > Square, and rename it to 'SnakeBody'. Change its color to something that'll contrast with the head, like dark green.

Scripting the Snake Movement

With our snake designed, it's time to bring it to life. In the Project panel, right-click and go to Create > C# Script. Name it 'Snake'. Double-click to open it in your preferred code editor. Here's the initial setup:

using UnityEngine; public class Snake : MonoBehaviour { public float speed = 0.2f; public Vector2 direction = Vector2.right; private List<Transform> _segments; private void Start() { _segments = new List<Transform>(); _segments.Add(this.transform); } private void Update() { // Placeholder for movement logic }}

Back in Unity, drag and drop the Snake script onto the SnakeHead in the Hierarchy. Now, let's handle the snake's movement. In the Snake script, replace the Update method with the following:

private void Update() { if (Input.GetKeyDown(KeyCode.UpArrow) && direction != Vector2.down) direction = Vector2.up; else if (Input.GetKeyDown(KeyCode.DownArrow) && direction != Vector2.up) direction = Vector2.down; else if (Input.GetKeyDown(KeyCode.LeftArrow) && direction != Vector2.right) direction = Vector2.left; else if (Input.GetKeyDown(KeyCode.RightArrow) && direction != Vector2.left) direction = Vector2.right; Vector3 targetPosition = transform.position + new Vector3(direction.x, direction.y, 0) * speed; transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime);}

This'll move our snake based on the arrow key inputs. But wait, our snake's not growing yet. Let's fix that.

Growing the Snake

To make our snake grow, we need to add a new body segment each time it eats. First, let's create a prefab for the snake body. Drag the SnakeBody from the Hierarchy to the Project panel. This'll create a prefab.

Now, back in our Snake script, let's add a method to grow the snake:

public void Grow() { Transform segment = Instantiate(this.SnakeBody); segment.position = _segments[_segments.Count - 1].position; _segments.Add(segment);}

Don't forget to add a public variable for the SnakeBody prefab at the top of your script:

public Transform SnakeBody;

Save your script and back in Unity, you'll see a field for Snake Body in the Inspector on the SnakeHead. Drag and drop the SnakeBody prefab into this field.

Creating the Food

Our snake needs something to eat. Let's create the food.

Designing the Food

In the Hierarchy, right-click and go to 2D Object > Sprites > Circle. Rename it to 'Food'. Change its color to something appetizing, like red. Position it anywhere within our game borders.

Scripting the Food Behavior

We want the food to appear in random positions within our game area. Let's create a new C# script called 'Food' and attach it to the Food object.

using UnityEngine; public class Food : MonoBehaviour { public Vector2Int gridPosition = Vector2Int.zero; public void RandomizePosition() { int x = Random.Range(-9, 9); int y = Random.Range(-4, 4); gridPosition = new Vector2Int(x, y); transform.position = new Vector3(x, y, 0); }}

Now, let's call this method when the game starts. In the Food script, add the following:

private void Start() { RandomizePosition();}

Handling Food Collision

We need to handle what happens when the snake eats the food. Back in our Snake script, let's add the following method:

private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Food")) { Grow(); other.gameObject.GetComponent<Food>().RandomizePosition(); }}

Don't forget to tag the Food object with 'Food'. To do this, select the Food object, go to the Inspector, click on Tag, and add a new tag called 'Food'.

Implementing Game Over Logic

It's not much of a game if you can't lose. Let's implement the game over logic.

Handling Border Collisions

First, let's handle collisions with the borders. We'll need to add a BoxCollider2D and a Rigidbody2D to our Border objects. Select all your Border objects, right-click in the Inspector, and choose Component > Physics 2D > BoxCollider2D. Do the same for Rigidbody2D, but make sure to set Body Type to Kinematic.

Now, back in our Snake script, let's add the following method:

private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Border") || other.gameObject.CompareTag("SnakeBody")) { GameOver(); }}

Don't forget to tag your Border objects with 'Border' and your SnakeBody prefab with 'SnakeBody'.

Implementing the Game Over Method

Let's implement the GameOver method. For now, let's just print a message to the console and stop the snake's movement:

private void GameOver() { print("Game Over!"); speed = 0f;}

Adding a Scoring System

To make our game more engaging, let's add a scoring system. We'll display the score on the screen and increase it each time the snake eats.

Creating the Score UI

First, let's create a UI text element to display the score. Right-click in the Hierarchy, go to UI > Text, and rename it to 'ScoreText'. Position it in the top left corner of the screen. You might need to adjust the Canvas settings to make sure it's displaying correctly.

Now, let's create a new C# script called 'GameManager' and attach it to an empty game object. In this script, let's create a public variable for the score and a method to update the score display:

using UnityEngine; using UnityEngine.UI; public class GameManager : MonoBehaviour { public int score = 0; public Text scoreText; private void Update() { scoreText.text = "Score: " + score.ToString(); } public void AddScore(int newScoreValue) { score += newScoreValue; }}

Back in Unity, select the GameManager object and drag and drop the ScoreText UI element into the Score Text field in the Inspector. Now, let's call the AddScore method in our Snake script when the snake eats:

private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Food")) { Grow(); other.gameObject.GetComponent<Food>().RandomizePosition(); GameManager.instance.AddScore(10); }}

Don't forget to make GameManager a singleton so we can access it from other scripts:

public static GameManager instance; private void Awake() { if (instance == null) instance = this; else Destroy(gameObject);}

Polishing the Game

Alright, we've got the basics down. Let's make our game a bit more polished.

Adding Background Music

First, let's add some background music. You can find plenty of free resources online. Once you have your audio file, import it into your project by dragging and dropping it into the Project panel.

Now, let's create an empty game object called 'MusicManager' and attach an Audio Source component to it. Drag and drop your audio file into the AudioClip field in the Inspector. Make sure to check Loop and Play On Awake.

Adding Sound Effects

Sound effects can make our game more satisfying. Let's add a sound effect for when the snake eats. Find a suitable sound effect online and import it into your project.

Create a new Audio Source component on the Food object and drag and drop your sound effect into the AudioClip field. Uncheck Play On Awake and Loop.

Now, in the Food script, let's play the sound effect when the snake eats:

private void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.CompareTag("Food")) { Grow(); other.gameObject.GetComponent<Food>().RandomizePosition(); other.gameObject.GetComponent<AudioSource>().Play(); GameManager.instance.AddScore(10); }}

Adding a Game Over Screen

Finally, let's add a game over screen. Create a new UI panel by right-clicking in the Hierarchy, going to UI > Panel, and renaming it to 'GameOverPanel'. Add some text to display a game over message and the player's final score.

Now, let's hide this panel until the game is over. In the GameManager script, let's add a method to handle the game over logic:

public void GameOver() { gameOverPanel.SetActive(true); Time.timeScale = 0f;}

Don't forget to add a public variable for the GameOverPanel and assign it in the Inspector. Also, let's call this method in our Snake script when the game is over:

private void GameOver() { print("Game Over!"); speed = 0f; GameManager.instance.GameOver();}

Conclusion

And there you have it! You've just created a classic Snake game in Unity. Along the way, you've learned about setting up a Unity project, creating game objects, scripting game logic, implementing a scoring system, and polishing your game with music and sound effects.

But remember, this is just the beginning. There's so much more you can do with this game. Here are a few ideas:

  • Add different types of food with varying point values.
  • Implement power-ups, like speed boosts or invincibility.
  • Create obstacles that the snake must avoid.
  • Add different levels with increasing difficulty.

The possibilities are endless. So, keep experimenting, keep learning, and most importantly, keep having fun!

FAQ Section

Q: I'm getting an error when I try to run my game. What should I do?

A: Don't panic! Errors are a normal part of game development. Check the console in Unity for more information about the error. If you're stuck, try googling the error message or asking for help on forums like Unity Answers or Stack Overflow.

Q: How can I make my snake move faster?

A: You can increase the speed of your snake by adjusting the speed variable in the Snake script. Remember, the higher the value, the faster your snake will move.

Q: How can I add more levels to my game?

A: To add more levels, you can create new scenes in Unity and load them using the SceneManager. You can find more information about this in the Unity documentation.

Q: How can I add a pause menu to my game?

A: To add a pause menu, you can create a new UI panel and add buttons for resuming, restarting, and quitting the game. You can then show and hide this panel based on player input. Unity has a built-in PauseMenu component that you can use as a starting point.

You Might Also Like:

  • Building Tetris Game in Unity: Tutorial


Citation

@article{building-snake-game-unity-tutorial, title = {Building Snake Game in Unity: Step-by-Step Tutorial 2025}, author = {Toxigon}, year = {2025}, journal = {Toxigon Blog}, url = {https://toxigon.com/building-snake-game-unity-tutorial} }


Related Articles

How to Create Realistic Movements in Unity: A Step-by-Step Guide

How to Create Realistic Movements in Unity: A Step-by-Step GuideWelcome to another exciting tutori...

2 months ago 10

Diving Into Shader Graph in Unity: A Hands-On Guide for Beginners

Diving Into Shader Graph in Unity: A Hands-On Guide for Beginners Welcome to the wonderful world of ...

1 week ago 17

How to Create Responsive Animations in Unity: A Comprehensive Guide

How to Create Responsive Animations in Unity: A Comprehensive GuideCreating responsive animations ...

2 months ago 22

Advanced Unity Animation Techniques: A Comprehensive Guide

Advanced Unity Animation Techniques: A Comprehensive GuideWelcome to the world of advanced Unity a...

2 months ago 8

Building Snake Game in Unity: Step-by-Step Tutorial 2025 (2025)
Top Articles
Latest Posts
Recommended Articles
Article information

Author: Saturnina Altenwerth DVM

Last Updated:

Views: 6310

Rating: 4.3 / 5 (44 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Saturnina Altenwerth DVM

Birthday: 1992-08-21

Address: Apt. 237 662 Haag Mills, East Verenaport, MO 57071-5493

Phone: +331850833384

Job: District Real-Estate Architect

Hobby: Skateboarding, Taxidermy, Air sports, Painting, Knife making, Letterboxing, Inline skating

Introduction: My name is Saturnina Altenwerth DVM, I am a witty, perfect, combative, beautiful, determined, fancy, determined person who loves writing and wants to share my knowledge and understanding with you.