A One-Stop Solution Guide to Learn How to Create a Game in Unity

The code that brings a video or computer game to life is game programming. Programming has changed in tandem with technology. Early on in the history of video games, programmers were often in charge of all development elements, including design. As hardware and software improved, development teams rose significantly.

This tutorial on "How to create a game in Unity" will make you accustomed to working with Unity 3D Software and Game Programming. 

What Is an Endless Runner Game?

Endless Runner is a video game where the player collects points and avoids obstacles while continuously going ahead. The primary aim is to reach the level's conclusion without colliding with or crashing into the obstacles. However, the level often repeats indefinitely, increasing in complexity until the player collides with an obstacle.

With this good brief on the Endless Runner, you must create your own Endless Runner Game in Unity 3D.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

3D Runner Game Project Creation

You must create a New Project.

/3D-Runner-Game-Create-Project-img1

You must then open your Unity Hub and click on New Project. 

3D-Runner-Game-Create-Project-img2.

Then, you will select 3D and name your Project 3DRunner. Choose where you want to create your project, and click on Create project.

3D-Runner-Game-Create-Project-img3.

Now, you will wait for unity to load up the project files and open the editor.

D-Runner-Game-Create-Project-img4

You must create a few folders like Prefab, Materials, and Scripts.

And this is your 3D Runner Game Project.

Now, go ahead and create a platform for your Player to run.

3D Runner Game Platform Creation

You will start by creating a tiled platform that will be saved later in Prefab.

3D-Runner-Game-Create-Platform-img1

1. You must create an empty game object and name it PlatformPrefab.

3D-Runner-Game-Create-Platform-img2.

2. Create a new Cube by right-clicking in the PlatformPrefab Object and selecting 3D Object to choose Cube. 

3D-Runner-Game-Create-Platform-img3

3. You will name this cube Platform, set its position to (0, 0, 0), and scale to (8, 0.4, 20).

Now that you have created a platform, you can create some obstacles for player objects to crash.

3D Runner Obstacles Creation

You will have six obstacle modifications, but you can make as many as you need:

D-Runner-Game-Create-obstacle-img1

  • You will make Six GameObjects inside the "PlatformPrefab" object and label them "Obstacle1", "Obstacle2", "Obstacle3", and so on.

Obstacle #1:

/3D-Runner-Game-Create-obstacle1-img1

  • Create a new Cube and place it inside the "Obstacle1" object for the first Obstacle.

3D-Runner-Game-Create-obstacle1-img2

  • You must name this new cube Obst1-Cube1 and scale the Cube to (8, 0.5, 3). And place it on the platform.

3D-Runner-Game-Create-obstacle1-img3

  • You will make a new material, name it "BlackMaterial," and modify its color to Black. 

3D-Runner-Game-Create-obstacle1-img4

  • Then, you must assign it to the Obst1-Cube1 (this is so that the Obstacle is distinguished from the main platform).

Obstacle #2:

  • You must make three cubes for the "Obstacle2" leaving one free spot at the bottom (the player is required to crouch to avoid this Obstacle).

3D-Runner-Game-Create-obstacle2-img1

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

  • You will name two cubes Obst2-Cube1 and Obst2-Cube2. And scale them as (1, 8, 1.5).

3D-Runner-Game-Create-obstacle2-img2

  • We must go on to name third cubes Obst2-Cube3 and scale them as (6, 7, 1.5).

3D-Runner-Game-Create-obstacle2-img3.

  • You must make a new material, name it "YellowMaterial," and modify its color to yellow. Then, you must assign it to Obstacle2 (this is so that the Obstacle is distinguished from the main platform).

3D-Runner-Game-Create-obstacle2-img4

  • And here is the complete obstacle 2.

Obstacle #3:

  • Next, build four cubes for Obstacle3, with one open area at the bottom and one in the middle so that the player can either jump or crouch.

3D-Runner-Game-Create-obstacle3-img1

  • You must name two cubes Obst3-Cube1 and Obst3-Cube2 and scale them to (1, 8, 1.5).

3D-Runner-Game-Create-obstacle3-img2.

  • Then, you must name one Cube as Obst3-Cube3 and scale it to (6, 2, 1.5). It will be at the top.

3D-Runner-Game-Create-obstacle3-img3

  • Then you must name one Cube as Obst3-Cube4 and scale it to (6, 1, 1.5). It will be at y=1.25 in height.

3D-Runner-Game-Create-obstacle3-img4

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

  • You must make a new material, name it "RedMaterial," and modify its color to Red. Then, you will assign it to the Obstacle3 (this is so that the Obstacle is distinguished from the main platform).

3D-Runner-Game-Create-obstacle3-img5

  • Here is the Obstacle 3

Next, you have Combinations of the above as obstacles 4, 5, and 6.

3D-Runner-Game-Create-obstacle4-img1

So, you have obstacle 4 as a combination of obstacles 1 and 2.

3D-Runner-Game-Create-obstacle5-img1

So, you have obstacle 5 as a combination of obstacles 1 and 3.

3D-Runner-Game-Create-obstacle6-img1

So, you have obstacle 6 as a combination of obstacles 2 and 3.

3D-Runner-Game-Create-obstacle-img2

Now, choose all the Objects inside the Obstacles and change their tag to "Finish." This process is required to detect when the Player and the Obstacle hit each other.

You now have a platform and obstacles. Now let's write a script to activate obstacles randomly.

3D Runner Game Obstacle Activation Scripts

Now, go to the Script folder and create a script "Simp_Platform.cs".

This script will be responsible for activating obstacles randomly.

Code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Simp_Platform: MonoBehaviour

{

    public Transform start;

    public Transform end;

   public GameObject[] obst; //Objects that contain various forms of obstacles that will be activated at random.

    public void ActRandomObst()

    {

        DeactAllObst();

        System.Random rand = new System.Random();

        int randomNum = rand.Next(0, obst.Length);

        obst[randomNum].SetActive(true);

    }

    public void DeactAllObst()

    {

        for (int i = 0; i < obst.Length; i++)

        {

            obst[i].SetActive(false);

        }

    }

}

3D-Runner-Game-obstacle-script-img1

  • You will attach this script to the PlatformPrefab Object by dragging it.

3D-Runner-Game-obstacle-script-img2

  • Now you must look at platformPrefab's inspector window. It has an obstacle component. So you must drag all obstacles to this component.

Next, write a script to generate the ground infinitely.

3D Runner Ground Generation Scripts

Now, create a script "Simp_GroundGen.cs".

This script will be responsible for infinitely generating the ground and keeping the score.

Code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.SceneManagement;

public class Simp_GroundGen: MonoBehaviour

{

    public Camera mainCamera;

    public Transform start; //this will Mark the location where the ground tiles will begin.

    public Simp_Platform PlatformPrefab;

    public float movingSpeed = 12;

    public int tilesToPreSpawn = 15; //no. of tiles should be pre-spawned

    public int tilesWithoutObst = 5; //How many tiles at the beginning should not have obstacles, good for warm-up

    List<Simp_Platform> spawnedTiles = new List<Simp_Platform>();

    int nextTileToAct = -1;

    [HideInInspector]

    public bool gameOver = false;

    static bool gameStarted = false;

    float score = 0;

    public static Simp_GroundGen instance;

    //start is always called before the first frame update

    void Start()

    {

        instance = this;

        Vector3 spawnPosition = start.position;

        int tilesWithNoObstTmp = tilesWithoutObst;

        for (int i = 0; i < tilesToPreSpawn; i++)

        {

            spawnPosition -= PlatformPrefab.start.localPosition;

            Simp_Platform spawnedTile = Instantiate(PlatformPrefab, spawnPosition, Quaternion.identity) as Simp_Platform;

            if(tilesWithNoObstTmp > 0)

            {

                spawnedTile.DeactAllObst();

                tilesWithNoObstTmp--;

            }

            else

            {

                spawnedTile.ActRandomObst();

            }          

            spawnPosition = spawnedTile.end.position;

            spawnedTile.transform.SetParent(transform);

            spawnedTiles.Add(spawnedTile);

        }

    }

    // The Update is always called once per frame

    void Update()

    {

        // We will Move the object upward in world space x unit/second.

        //Increase speed the higher score we get

        if (!gameOver && gameStarted)

        {

//This will increase the speed as time passes

            transform.Translate(-spawnedTiles[0].transform.forward * Time.deltaTime * (movingSpeed + (score/500)), Space.World);

// this will keep track of score            

score += Time.deltaTime * movingSpeed;

        }

        if (mainCamera.WorldToViewportPoint(spawnedTiles[0].end.position).z < 0)

        {

            //We will Move the tile to the front if it's behind the Camera

            Simp_Platform tileTmp = spawnedTiles[0];

            spawnedTiles.RemoveAt(0);

            tileTmp.transform.position = spawnedTiles[spawnedTiles.Count - 1].end.position - tileTmp.start.localPosition;

            tileTmp.ActRandomObst();

            spawnedTiles.Add(tileTmp);

        }

// if the game is over or did not start, then this will prompt us with instructions to press space to play again 

        if (gameOver || !gameStarted)

        {

            if (Input.GetKeyDown(KeyCode.Space))

            {

// if the game is over, then it will show the current score and give instructions to restart

                if (gameOver)

                {

                    //this will Restart the scene displayed currently

                    Scene scene = SceneManager.GetActiveScene();

                    SceneManager.LoadScene(scene.name);

                }

                else

                {

                    //This will Start the game file again

                    gameStarted = true;

                }

            }

        }

    }

// A function responsible for displaying instructions and score

    void OnGUI()

    {

// if game over

        if (gameOver)

        {

// to set the text color red

            GUI.color = Color.red;

// dimension for the text box 

            GUI.Label(new Rect(Screen.width / 2 - 99, Screen.height / 2 - 99, 198, 198), "Your Game is Over\nYou scored: " + ((int)score) + "\nYou can Press 'Space' to restart the game");

        }

        else

        {

            if (!gameStarted)

            {

                GUI.color = Color.red;

                GUI.Label(new Rect(Screen.width / 2 - 99, Screen.height / 2 - 99, 198, 198), "You can Press 'Space' to start");

            }

        }

// this will display real time score in green color

        GUI.color = Color.green;

// this will display the score

        GUI.Label(new Rect(5, 5, 200, 25), "Your Score: " + ((int)score));

    }

}

3D-Runner-Game-GroundGen-script-img1

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

  • You need to construct two GameObjects for the Start Point and End Point, which are placed at the start and end of the platform.

3D-Runner-Game-GroundGen-script-img2

  • Now, you will add these objects to PlatformPrefab's Simp_Platform component.

3D-Runner-Game-GroundGen-script-img3.

  • Now you must create a game object and name it SimpGroundGen. And you will attach Simp_GroundGen.cs to this game object.

3D-Runner-Game-GroundGen-script-img4.

  • You will Change the Main Camera position to (10, 1, -9) and change camera rotation to value (0, -55, 0)

3D-Runner-Game-GroundGen-script-img5

  • You must create a new GameObject, call it "StartingPoint," and change its position to (0, -2, -15).

3D-Runner-Game-GroundGen-script-img6

  • Now you must go to the prefab Folder, and you will drag the PlatformPrefab game object to this to create a prefab.

3D-Runner-Game-GroundGen-script-img7

  • Now, you must delete the PlatformPrefab from the hierarchy tab. And your "PlatformPrefab" Prefab is ready.

3D-Runner-Game-GroundGen-script-img8

Get the Coding Skills You Need to Succeed

Full Stack Developer - MERN StackExplore Program
Get the Coding Skills You Need to Succeed

  • Now, you will select the "SimpGroundGen" Object, and in Simp_GroundGen, we will assign the Main Camera to the camera, the StartingPoint Object to the Start Point, and the PlatformPrefab to the Prefab.

3D-Runner-Game-GroundGen-script-img9

Now that you have created the game's complete environment, create a player object.

3D Runner Player Object Creation

Now, you will create a “PlayerObject” Game Object. 

3D-Runner-Game-Create-Player-img1

You will then create a new sphere by right-clicking on the PlayerObject Object and selecting 3D Object to choose Sphere.

3D-Runner-Game-Create-Player-img2

You must make a new material, name it "BlueMaterial," and modify its color to Blue.

3D-Runner-Game-Create-Player-img3.

Then, you will assign it to the Player.

3D-Runner-Game-Create-Player-img4

Now you will remove Sphere's Sphere Collider component.

Now, you have created the player object. Next, create a script to control the Player.

3D Runner Player Control Scripts

Now you will create a new script called "Simp_Player.cs". This script will let the Player jump when you press the W key and crouch when you press the S key.

Code:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

[RequireComponent(typeof(Rigidbody))]

public class Simp_Player: MonoBehaviour

{

    public float gravity = 20.0f;

    public float jump_Height = 2f;

    Rigidbody r;

    bool grounded = false;

    Vector3 defaultScale;

    bool crouch = false;

    //method start is always called before the first frame update

    void Start()

    {

        r = GetComponent<Rigidbody>();

        r.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ;

        r.freezeRotation = true;

        r.useGravity = false;

        defaultScale = transform.localScale;

    }

    void Update()

    {

        // Jump

        if (Input.GetKeyDown(KeyCode.W) && grounded)

        {

            r.velocity = new Vector3(r.velocity.x, CalculateJumpVerticalSpeed(), r.velocity.z);

        }

        //Crouch

        crouch = Input.GetKey(KeyCode.S);

        if (crouch)

        {

            transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(defaultScale.x, defaultScale.y * 0.4f, defaultScale.z), Time.deltaTime * 7);

        }

        else

        {

            transform.localScale = Vector3.Lerp(transform.localScale, defaultScale, Time.deltaTime * 7);

        }

    }

    // Update is called once per frame

    void FixedUpdate()

    {

        // We apply gravity manually for more tuning control

        r.AddForce(new Vector3(0, -gravity * r.mass, 0));

        grounded = false;

    }

    void OnCollisionStay()

    {

        grounded = true;

    }

    float CalculateJumpVerticalSpeed()

    {

        // From the jump height and gravity, we deduce the upwards speed 

        // for the character to reach the apex.

        return Mathf.Sqrt(2 * jump_Height * gravity);

    }

    void OnCollisionEnter(Collision collision)

    {

        if(collision.gameObject.tag == "Finish")

        {

            //print("GameOver!");

            Simp_GroundGen.instance.gameOver = true;

        }

    }

}

3D-Runner-Game-Player-Script-img1

  • You must attach the “Simp_Player” script to the "PlayerObject" object.

3D-Runner-Game-Player-Script-img2.

  • You will click on add component in PlayerObject's inspector tab, select Physics, and choose BoxCollider Component to the "PlayerObject" object.

3D-Runner-Game-Player-Script-img3.

  • Finally, place the "Player" object slightly above the "StartPoint" object, right in front of the camera.

3D-Runner-Game-Player-Script-img4.

Now, you can Press W to make the player Jump.

3D-Runner-Game-Player-Script-img5

Now you can Press S to make the player Crouch.

With this, you have successfully created your first Game.

Accelerate your career as a skilled MERN Stack Developer by enrolling in a unique Full Stack Developer - MERN Stack Master's program. Get complete development and testing knowledge on the latest technologies by opting for the MERN Stack Developer Course. Contact us TODAY!

Next Steps

The next lesson in your C# training can be "C# Rest API." REST stands for "Representational State Transfer," meaning REST is a style of building distributed systems based on rules describing and talking about network resources. RESTful services talk to each other through HTTP (HyperText Transfer Protocol). The REST system talks to other systems through web resources identified by URIs.

Simplilearn is the world's most popular online Bootcamp for developing skills in the digital economy, and it's here to assist you in doing just that. Digital marketing and data science are just two topics we cover extensively in our online courses.

Simplilearn teamed with the Caltech CTME and the Indian Institute of Technology, Kanpur, to deliver their Software Development courses. These courses cover the fundamentals of data structures and algorithms and more advanced subjects such as Competitive Programming. As a software engineer, you will learn about data structures such as trees, graphs, and queues.

The comments section below is open for questions and comments about this 'How to create a game in Unity' tutorial. Happy learning!

About the Author

Vaibhav KhandelwalVaibhav Khandelwal

Vaibhav Khandelwal is a proactive tech geek who's always on the edge of learning new technologies. He is well versed in competitive programming and possesses sound knowledge of web development. He likes to read fictional and sci-fi novels and likes to play strategy games like chess

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.