How To Make A Simple Game With Unity : For Absolute Beginners
Tags: unity3d, tutorial, gamedev
Published: 2021-03-14 06:44:56

> 
Hi there. In here,we are going to make a simple game(First game that I made at 12 years old..xD)I published it on WebGL recently.That is not so much good.But we will make a game which is better that it!Here it is(Play it only for take an idea about our game.We are going to make a better game that it;). If you join us with Discord, you will get only 2 or 3 days to make this game.  [Play Color Cube 3D here.](https://play.unity.com/mg/other/color-cube-3d ) and [Join Us here](https://discord.gg/Eaau4cU4) 
## Introduction And Download Unity


![unity3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlk97ztil2j4tdhktp71.jpg)
 
***What is Unity?***

Unity is a cross-platform game engine developed by Unity Technologies. 51% of game is the play store are made with unity. In this game, we are going to use Unity personal edition.

***Why Unity***

There are many reasons. It is fairly easy to learn and use more than other engines.And you will never get alone with bugs,questions and anything in Unity.They have many official web sites that can help you such as Unity [Answers](https://answers.unity.com/index.html), Unity [Forums](https://forum.unity.com/) and many more.

***Download Unity*** 

Go [there](https://unity3d.com/get-unity/download) to download Unity or to to www.unity3d.com .(Download with Unity Hub)You will need 'Visual Studio' too. 

***Create your project***
![unity](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5tgblshszg1mpuo16r5j.PNG)
 
In unity hub, you can see a 'Create' button.Click on it. In here,we are going to make a 3D game. Name your project as 'Color Cube 3D'  or something and select a location. And hit "CREATE"!

### Train You Eyes..


![Unity1.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1615179796532/7Tcx7_mv3.png)

Now you can see some windows as 'Hierarchy', 'Inspector', 'Scene', 'Game', 'Project' and more

**Hierarchy**

All GameObjects in the scene is in there. If you select a game object in hierarchy, it will also selected in scene. We can make a GameObject by right clicking in this window. More in future:D

**Inspector**

All the components(Scripts and others)added to a GameObject is in here.When a GameObject is selected in Hierarchy or in the Scene, all the components in that GameObject will show in here.

**Scene**

This is the scene view of the game. All the things are done in Scene view.Move objects, Setting up the scene and more.

**Game**

This is the full game view. Game view is depending on camera. You can't edit anything in Game view. When you hit the play button, you can play the game in Game view. You can't save anything while play. If you changed something when the game is going on, its only for that time. When game is stopped, you will lost your changes.

**Project**

Scripts, Prefabs, Materials, Sprites, Animations, Sounds and all are in Project window. All of these are 'Assets.' You can use folders to make it tidy.

**Animation**

You have to make all the Animations here.

**Console**

In console,it will show you all the errors and bugs in scripts and the Editor.Also "Debug.Log" messages are in there.



*Don't worry if you didn't understand somethings.All will explained!Stay relax and funny!And take a deep breathe and ready to start!
*

### Set Up Your Scene

**Main Camera** - Game view is depending on Main Camera.You can move,rotate and anything to camera to set up the view

**Directional Light** - This is the main light souse to the game.You can change it too but nothing will change.If you want to see, select Directional Light and press 'Del'. Did you see? Now press Ctrl + Z.

**Making Game Objects**

    
- Go to Hierarchy and right click. 3D Object > Cube.You can see a cube on the scene and the game.Rename your cube as "Player".(Normally cube will appeared in front of camera, so it can be seen in game view.If not,adjust your camera or cube.)
    
- Move your gameObject if you want.There are 3 axis in Blue, Red and Green. Blue is z, Red is 'x' and Green for 'y'.

- 
And,in inspector window,there is the scale of the cube.You can change it.I will fix it to 5x5x5.
    

- To create a color material,go to project window, right click and Create > Material. And make your color by click the rectangle in white color.(By clicking it,color mixer appear.)

- Next, drag and drop your color material to the cube
- Add 'Player' tag to your Player Cube.
![unity5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t57k0lsi9mkvzbachx7q.png)
 
- After that make another cube and rename it as "Ground". Give him a color if you want.Now, make the 'Ground's scale somewhat big.

  
- Now let's add a 'slipary' nature for our ground. To do that,right click on Project tab, Create > Physics Material. Rename Physics Material as 'slipary'.

  
-  And next, Go to inspector window of 'Player'. And there is a button called 'Add Component'. Click it and type 'Rigidbody' in search bar.And click on Rigidbody.Now Rigidbody is an component of 'Player'. 

- One more thing.to make the game's background as a solid color,go to Main Camera's inspector window and change 'Clear Flags - Skybox' to solid color.And choose your color in 'background' color mixer.
Your game view would be like this,
![uni6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eadkxffu2kcn2w7x6jrf.png)
 
*Tips*

- To zoom in/out an object,select the object an press 'F'.
   
- To look around,Click left mouse while pressing 'Alt',and look around.(Like a shooting game.Difference is you have to keep pressing mouse and Alt)
   
- Use WASD key to move while right clicking mouse

- To maximize Game view,press Shift + Space.

### Adding Player Movement

 Let's make the player's movement!

- Go to Project window,right click, Create > C# Script.Name your script as 'PlayerMovement'.Keep remember - Don't use spaces and special characters.Unless it will give errors. 

-Then double click on script.It will open in in Visual Studio and will look like this.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

``` 

You may be a beginner for coding too. Don't think more about these tags and functions.
Remove the 'void Start()' function.


- First of all,we need to make some public variables for Player's rigidbody and to 'forwardforce' and 'sideforce' amounts. So we can change them in inspector easily.

```
 public Rigidbody Rb;
 public float forwardforce = 2000f;
 public float sideforce = 500;

``` 

- After that,change 'void Update()' function to 'void FixedUpdate()'.And let's add a forward force to our Player like this . 

``` 
    void FixedUpdate()
    {
        // Adding force to game object
        Rb.AddForce(0, 0, forwardforce * Time.deltaTime); //Since every desktop/laptop has not same number of Frames Per Sec ,we use Time.deltaTime.

    }
``` 

- Now save script (Ctrl + S) and go to unity.Wait till it update scripts.(A loading circle will work in right corner of Editor.That means it is not ready to play)Don't forget to drag and drop your script to Player. After that, in player's inspector you can see some new slots like this,
![uni7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iqco6cy554egncfv0hqw.png)
 


- In 'Rb' slot ,drag and drop your Player's Rigidbody component.And hit PLAY button or press Ctrl + P. Now you see what happens.Adjust your speed and see if you want. Now,Let's add a sideForce by pressing keys.

```
  if (Input.GetKey("d"))
        {
            Rb.AddForce(sideforce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);

        }
        if (Input.GetKey("a"))
        {
            Rb.AddForce(-sideforce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
        }
        if (Input.GetKey("s"))
        {
            Rb.AddForce(0, 0,-1000 );  // 0 to x, 0 to y and -1000 to z. Ordered as x,y,z.
        }
        if (Input.GetKey("w"))
        {
            Rb.AddForce(0, 0, 1000);
        }
``` 

- Adjust player's speed as you wish.But Cube still rotates no? Freeze rotation in 'x' axis, using Rigidbody's Constraints.
![uni8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1qbfhplu995jrx8tc3y4.png)
 

Now, Player's Movement is Okay!


### Make Camera To Follow Player


- This is simple.Create another C# Script and Name it as 'CameraFollow' or any name.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{
    public GameObject playercube; // Making a public variable for Player

    private Vector3 offset;
    // Start is called before the first frame update
    void Start()
    {
        offset = transform.position - playercube.transform.position;  
    }

    // Update is called once per frame
    void LateUpdate()
    {
        transform.position = playercube.transform.position + offset; //Make Camera to player's transform position
    }
}
``` 

- Save the script and go to Unity.Wait until it updates.Drag and Drop the script to Main Camera.Now, you see new slot in Inspector. Drag and drop Player cube to there. Hit PLAY !

### Make Like Cubes and Obstacles(Main Level Design)


- This take sometime.According to our game,we have to put like cubes and Obstacle.Make Like cubes in Player's same color and Obstacle in Black color. Add Rigidbody to all of them.Set the mass as 0 for small ones.
-Make a tag named obstacles and add it to a obstacle.They may in different sizes.It is easy to make a one like cube and a Obstacle first and add those. 

- Make an Empty GameObject(Hierarchy > Create Empty). Rename it as 'Like Cubes'. Make another as 'Obstacles'. Next,drag and drop your Like Cube to 'Like Cubes' gameObject and Obstacle to 'Obstacles' gameObject.Now, they are children of 'Like Cubes' and 'Obstacles'. Now create your first level by duplicating those. 

- If you make a one row,you can select them all and duplicate.So it won't get so much time.Remember to make it somewhat difficult.

Here is mine..,
![scene](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cl1mpi9j1ramxyg87igy.png)
 
### Game Over..

Let's make the GameOver part

**Making Game Over Panel**

- First, Let's create a GameOver panel. Hierarchy > UI > Panel.Set the Panel Size and Color.In Color Mixer, Set 'A' to 255.You can see the difference.It is useful when making Animation.Now create a Text as GameOver.(Hierarchy > UI > Text). Make 2D view toggle on.

- To add Fonts, Project > Import New Asset.Remember to make Canvas Scaler to "Scale with screen size".
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zcapyd6obb2njary4zgg.jpg)
 
Here is mine one..Making a prefab for GameOver panel will  be better when making new levels.To make a prefab,Drag and drop GameOver panel to 'Project' tab.

![gmae ovber](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccv3rmw0ulvmhqpsjjtu.png)
 
- Making a prefab for GameOver panel will be better when making new levels.To make a prefab,Drag and drop GameOver panel to 'Project' tab.By making a GameObject to a prefab,we can change all the GameObjects once.

**Game Over**
GameOver and Level Completed functions should be in GameManager.Let's make it.


- Make a Empty GameObject as GameManager. 
- Make a Script called GameManager.Drag and drop it into GameManager Object. And make it as a prefab(The prefab figure will be different).
- Go to File > Build Settings. Drag and Drop your scene to 'Scenes in Build'.
![build](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8rbjrs0kfo5w6ncpqkqz.png)
 

In GameManager,

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;


public class GameManager : MonoBehaviour
{
    bool gamehasEnded = true;

    public GameObject GameOverPanel;
    public void GameOver()

    {

        if (gamehasEnded == true)

        {
            gamehasEnded = true;
            GameOverPanel.SetActive(true);
            Restart();



            void Restart()
            {
                SceneManager.LoadScene(SceneManager.GetActiveScene().name);
            }



        }



    }   }

``` 

- If you deal with scenes,you can't do anything without '*using UnityEngine.SceneManagement;*'tag.

- Save the script and go to Unity.In GameManager's inspector,there is a slot named 'Game Over Panel'.Drag and drop Game Over Panel to there.

- Make a GameOver script,

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameOver : MonoBehaviour
{
    private void OnCollisionEnter(Collision collisionInfo)


    {
        if (collisionInfo.collider.tag == "Obstacle") //If collides with a object having OBSTACLE tag..
        {
            FindObjectOfType<GameManager>().GameOver();//Call GameOver function in GameManager
            FindObjectOfType<PlayerMovement>().enabled = false;//disable PlayerMovement script when gameover
        }
    }
}
``` 

- Drag and drop GameOver script into Player.Now you can see, if you hit a obstacle,Panel will show and Game will Restart 

**GameOver when Player Falls**
-In our Player Movement script,add 

```

       if (Rb.position.y < 0.1f) //if Player's position lesse than 0.1f,Game over..

        {
            FindObjectOfType<GameManeger>().GameOver();

        }
``` 
Now,Game Over part is finished!

### Level Complete

Let's make level Complete part..

-Make a Cuboid(from a cube;)which is set to ground's width.Name it as 'Game End Trigger'. Scale it Like this,
![Game end](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ggfcfenscum4fta7l5m.png)
 
- Now disable the 'Mesh Renderer'.So it will get Invisible.In 'Box Collider',enable 'Is Trigger'.
- Make a LevelComplete panel too.
- Make a script as 'GameEndTrigger'.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameEndTrigger : MonoBehaviour
{

    public int levelIndex;
   
    private void OnTriggerEnter(Collider other)

    {

        if (other.tag=="Player")
        {
            FindObjectOfType<GameManager>().LevelComplete();
            FindObjectOfType<PlayerMovement>().enabled = false;
           SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);//Load Next Level in Build Setting.
          
           
        }

       
    }
     
}
``` 
In GameManager,Add

``` 
public GameObject LevelCompletedPanel;


    public void LevelComplete()

    {
        LevelCompletedPanel.SetActive(true);
    }
``` 


- Now save and go to Unity. Apply LevelCompletePanel to GameManager's slot. Hit PLAY and play the game. When Player passes the Trigger, Level Complete UI will appear. Make Prefabs from GameOver Panel, LevelCompletePanel and GameEndTrigger.
-Next ,it is time to make next levels. Select your first level and press Ctrl + D. So levels will duplicate.Change next levels and make them more hard.I will make 3 levels for now. You can make more!

### Animations..
Let's make some animations for our panels.
- Open Animation tab.(Ctrl + 6)Select the GameObject(Panel)and hit "CREATE".(Make a Folder called 'Animations project tab.)
- Hit Record Button first. And go to Panel's color mixer.Set 'A' to 0.
![co1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8s1donq12apb1a4rbkxm.png)
 
-Now go to 40 seconds and set 'A' to 255. Now you have make a Fade Animation for your GameOver Panel.
![co2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggd8pf1ahl8egpph4bro.png)
![co3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9yk7fa1x2wogbkw9rzfm.png)
  
-Play the animation and see.We don't need to loop the animation.Disable 'Loop Time'.
![animloop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b2v0fcn4e116o43tt4lo.png)
 
- Do the same thing to LevelComplete Panel.One thing should be added.We have to add an event to load 'Next Level'. To do that,go to end of the Animation and hit 'Add Event'. But we want a script for that;) Make a C# script called "New Level Load".
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class NewLevelLoad : MonoBehaviour
{

    public void NextLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); //Load the scene which has scene index +1 than the current scene
    }

}
``` 
- Drag and drop the script into LevelComplete panel.Now, hit 'Add Event'(only if you didn't add it before;). Scroll down and select 'Next Level' function.
![anim](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xc6b0h2n5m79zg0odygk.png)
 
 Forgot one thing:D .Add your new levels to 'Scenes In build'..
- Play the Game and see...Well done!

### Adding Menus, Buttons and Audio

**Start Menu**
- Let's make a Start Menu first. Make a scene called 'Start Menu' (Project > Create > Scene). Make a panel and design it as you want.
-Add 2 buttons as 'Start' and 'Quit'.(Hierarchy > UI > Buttons)
-Make a empty object as 'Buttons'
-Create a script as 'ButtonsInTheMenu'.

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class ButtonsInMenu : MonoBehaviour
{
  public void StartGame()
    
  {
        SceneManager.LoadScene(1); //Load first scene
  } 

  public void Quit()
  {
       Application.Quit(); //Quit the application
  }

}
``` 

- Drag and drop the script to 'Buttons' object.
- In buttons, you can see a something like 'On Click()'. Click '+'.
- Drag and drop 'Buttons' GameObject in to that and select 'Start Game' function to 'Start' button and 'Quit' function to 'Quit' button.
- Make it as a prefab
![start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f02svmhfuwxit8qbthd1.png)

**Game End Menu**

-  Make a scene as 'Game End Menu' and design it as you want.
- Make 2 buttons as 'Quit' and 'Restart'.
- Use same 'Buttons' object and script.(Add prefab)
- Add 'Quit' button and add same function as 'Start' menu.
- Make a 'Restart' button.In 'ButtonsInMenu' script,

```
public void RestartGame()
    {
        SceneManager.LoadScene(sceneBuildIndex: 1); //Load 1st level
    }
``` 
- Add 'Restart Game' function to that button.Check and see. Nice! 

**Add a Music**
- Project > Import New Asset > Select your audio file. Make a Empty GameObject called 'SoundManager'. Drag and drop your audio file to that.
- Make it as a prefab and add it to next levels.Well done! Only few steps to finish our game..

### Finishing
- End of our game. Let's add some designs.(I will only add a one;)

**Make two support bar in Level 1.**
 - Make 2 GameObjects(Cuboids from cubes). They are the support bars.Fix them on both sides of the ground(so Player won't fall. But don't add it for future levels.You know why.. ;)
 - Make a material. To make it glow, enable 'Emission'. And adjust your color as you wish.

**Build Your Game**
- So, this is the end.Now let's build our game.To do that, File > Build Settings.Add all of your scene in order. 
![2more](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhzcagikw06yo3j0tkuu.png)
 

-Go to 'Player Settings' and Name your Game and Company.This is not essential for build.You can give a Badge too.
![finish](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/daxsxv4zfd84s8s5sdqb.png)
 
-Next, Select your platform and hit 'Build'. Make a new folder(If you haven't) and select.Wait till it finish build. That's it!