Introduction: Make a Game in Unity3D | Fundamentals of Game Making in Unity3D

Hello everyone! I hope you have great day! Because we are gonna do something amazing! And that is making a game! awesome, ha? First we need software, aren't we? go to unity3d.com and press "Get Unity" button to go to download page after that you'll see the plans choose the personal edition and wait until the download assistant downloads completely(Note: Please DO NOT buy the Plus or Pro versions if you are just starting out) after download completes follow the instructions until it come to the feature selection part, see the image above to select what we need for now.

Step 1: Creating a New Project

After the installation completes, open up unity and you'll see a menu pop up with existing projects, first of all press the "New" button on top right another menu will pop up asking for the details such as:

name of the project

location of the project folder

3D or 2D project

Step 2: Brief Tour of the UI

and the editor opens and you'll see this complicated mess... well for a beginner at least we need to know what these tools and tabs and stuff do don't we? this is list of the what does what(some of these aren't on the picture because of other tabs):

Hierarchy : All the game objects that are present in the scene

Project tab: All the files and assets in the projects folder

Inspector : properties of the object

toolbar : tools and options

Inspector : properties of the object

Not in the picture:

Game : the tab where you can play the game and see the camera view

Console : used for debugging and will give errors when there is a bug in the code

Step 3: Programming Languages in Unity3D

Now we need to know a programming language don't we? of course we do but not any of them it has to be a specific one and that's C# reason we will use this is because unity supports only 2 languages UnityScript(Implementation of JS to Unity) And C# but in recent days unity announced that UnityScripts will no longer supported on Unity3D reason is that there isn't much users use UnityScript so C# is the only choose.

Enough of that UnityScript history, Let's look at C#! First we need a so called IDE or (Integrated Development Environment) we will use Visual Studio Community Edition from this link www.visualstudio.com.

Step 4: Brief Introoduction to C#

Now before we start programming, we need to learn basics, now C# is not the easiest but not the hardest, now let's learn the basics :

Comments And Description:

Now when we write code and after few weeks we come and want to change something but you forget everything you did! This is why we use so-called Comments there are there to remind or inform others what this line does, to make a comment there is 2 ways first for a single line and secondly is for multiple lines of comment.

First Way: After we write the line of code at the very end we type 2 slashes (//) after this everything is considered as a comment until you go to new line which is useful for informing people what this line does but not for long descriptions

Second Way: here we don't use // instead we use /* to start it and */ to end it, after /* everything considered as a comment including all the lines and code after it and so on which is used to disable certain places in the code temporarily to try or implement something new.

by the way, any comment is not a part of the final executable and will be ignored by the compiler and will only be present in the source code

Using :

at the very beginning of our code we have few lines starting with using, we use using to declare namespaces we want in our code, for example, using System; is a core namespace and used in most programs.

Namespace :

Namespaces are used in C# heavily in two ways, the first .NET framework uses namespaces to organize its many classes as follows:

System.Console.WriteLine("Hello World!");

System is the namespace and Console is the class and the WriteLine is method, but if we do this for every line of code it will be long and little messy so here we use using as follows:

using System;

Namespaces are extremely useful in organizing code by creating your own! how? by creating a new C# script in the same solution/project and calling the namespace in that scripts with "using".

Classes :

classes are used to store methods and variables and every C# scripts needs to have 1, inside of a class we can define variables create methods and constructs, now if we create a sub-class and create some variables inside of it and if we create a constructor we can define variables while we make an instance of it, example in the picture.

Static Classes :

Static Classes are the same as non-static ones but has a huge difference that makes it different, and the difference is that Static Class cannot be instantiated so you can't use new keyword to create an instance of the object and only the original instance can be accessed which is useful for the methods inside of a class that takes an input and returns back output and cannot contain instance constructors.

Dynamic Classes :

If a class does not start with static keyword then it means it is a dynamic class there isn't a keyword for dynamic classes and unlike static classes, you can create instance of it and can have Instance constructors

instancing :

to instance a dynamic class first type the name of the class and then the name of the instance followed by = sign and new keyword and the name of the class followed by open and close brackets and if your class has constructors then you can assign them inside of the curly brackets, example :

NameOfTheClass NameOfTheInstance = new NameOfTheClass(int 2, float 6.5f, int 55);

Invoke :

“Invoking” refers to calling a method, there are 2 ways to use it, first is 1 time only second way is repeating

to do a single time invoke you first type invoke followed by brackets and inside of the brackets name of the method inside of double quote and then a comma and then the time it should wait before executing in seconds, example :

invoke("ExampleMethod", 2);

Secondly, we have InvokeRepeating, which takes 3 parameters first is the name of the method we want to call and a comma then the time it should wait before calling for the first time and a comma then how much time it should wait after every call before calling again, example :

InvokeRepeating("ExampleMethod", 2, 1);

to cancel a repeating invoke we use InvokeCancel and the name of the method inside of double quote, example :

InvokeCancel("ExampleMethod");

Method :

Methods are the fundamental pieces of our code and make up most of it and what does the work and A method is a code block that contains a series of statements. A program causes the statements to be executed by calling the method some methods may or may not require argument for example if I made a method that will find a circumference of a circle I have to give the method Diameter or the radius of the circle, but some of them may not want for example a method that will give the character point and check if the point count exceeds a limit character will level up, a useful things you can do with methods is to organize your code by putting certain sections of the code in a method and calling it via invoke.

Now, this is not everything that you need to know to make a game because it would take weeks, months or even years to learn everything! building a game isn't an easy task you need to so many things and it is good to ask if you don't understand the number one rule in programming is to not give up don't even think about!

Step 5: Let's Make a Game!

Now, Let's start on making the game! now we don't want to make characters models etc. because it will take a long time to finish and I want to teach you fundamentals of making a game in Unity3D but still when you finish it you will be extremely happy! because you did something awesome! Now let's get started!

First, we need to choose a genre, theme and the game play, I chose a simple fps where player shoots the targets

Step 6: Creating the Enviroment

Platform :

First, Make a new cube by going Create>3D Object>Cube in hierarchy and position it at the origin (0, 0, 0) and scale to(5, 0.5, 20) then Create a folder called materials by going Create>Folder in Project Tab and inside of it Make a Material by going to Create>Material in projects tab and drag it onto the cube nothing will change until we give the Material a color by clicking the Material And then the box next to the albedo.

Enemy And Player Base :

make a cube and resize it then move it to the corner, follow this until you have a base that looks like the one in the picture, and resize the final cube which is the front one so it will fit between 2 cubes, then select all and Duplicate it with CTRL + D and move it to the other side of our plane and move the front wall to the opposite side, now let's create two new materials for our bases, I chose traditional blue and red but you can choose anything you want, now drag the materials to the cubes and that's it! now this step is optional but really recommended, create 2 empty game objects and name them player base and enemy base and drag the walls of the enemy and player base into them, what we did here is to organize the game objects so we understand what is what.

now let's save our scene by going File>Save Scene or CTRL + S a window will pop up asking you to where to store create a new folder called scenes and save the scene as scene1

Step 7: Creating the Player

Create a sphere and move the camera inside of the sphere and then make the camera child of the sphere by dragging it into the sphere in hierarchy and select the sphere and move it to the base and I the inspector press add component>Physics>Rigidbody and change the options like shown in the picture

Go to next step for the programming

Step 8: Creating the Player Movement Scripts

Now before we can start coding we need to know what we want from our code, will it handle movement? will it handle Level System? and how it gonna do that? now this is what we want from our code :

It will handle movement in 1 axis

with a variable speed

now let's write the script! create a folder in the project tab called scripts and create a new C# script and open it when you first open it there will be some code in there, just remove these lines :


    after that file should look like this :

      why we removed those lines? because we want to code from the ground up and it would be easier this way for some, no everything goes under "public class CharMovement : MonoBehaviour" and we define namespaces will be used at the top

      so let's go save it with CTRL + S and go back to unity and drag the script into the sphere and not the camera, now in visual studio type this scripts which looks little complicated but you can understand what is does with the comments next to it :

      using System.Collections;
      using System.Collections.Generic; using UnityEngine; public class CharMovement : MonoBehaviour { //Assigning public variables public float Speed; //Assigns a public variable for speed that can be accessed from the inspector //Assigning private variables private Rigidbody rb; //Assigns a private variable as rigidbody assembly refrence //Start Function runs once before the first frame update private void Start() { //Assigns rb as a assembly reference for rigidbody rb = GetComponent(); } //FixedUpdate runs before every frame update and has a fixed speed private void FixedUpdate() { //Gets input value for the horizontal axis and stores it on a Float variable float movH = Input.GetAxis("Horizontal"); //Makes a new vestor3 with movH as the X Axis and normalizes it so it says the length does matter and multiplies it with speed variables Vector3 Movement = new Vector3(movH, 0f ,0f).normalized * Speed; //Applying the movement with Rigidbody.AddForce rb.AddForce(Movement); } }

      Step 9: Creating the Gun

      First, make 2 cubes and resize them and positioning them like in the picture and group them with an empty game object and move them to side of the player and make it child of the player.

      let's make a cross hair, create a UI element by going to Hierarchy>UI>Image and choosing knob as sprite and setting width and hight to 5

      Now, before we make the gun Script let's understand how it works, now we shoot an invisible ray that will hit the object and give us some information with that we can check if the object is the enemy if so disable it

      so th code is simple it will check if the mouse button is pressed if so it will shoot a ray and then it will check if the object has the tag enemy and if so it will disable it if not it won't do anything :

      using System.Collections;
      using System.Collections.Generic; using UnityEngine; public class GunScripts : MonoBehaviour { //Assigning Public Variables public Camera FPCam; //Assigining a public variable as a refrence for our player camera private float maxDistance = Mathf.Infinity; //assigning variable for maximum distance that equals infinity // Update is called once per frame void Update () { if(Input.GetButtonDown("Fire1")) //Checks if the left mouse button pressed { Shoot(); } } private void Shoot() { RaycastHit hit; if(Physics.Raycast(FPCam.transform.position, FPCam.transform.forward, out hit, maxDistance)) { print(hit.transform.tag); if(hit.transform.tag == "Enemy") { hit.transform.gameObject.SetActive(false); } } } }

      The code that allows us to send a ray is :

      Physics.Raycast(FPCam.transform.position, FPCam.transform.forward, out hit, maxDistance)

      there are few arguments let's look what they mean:

      first is "FPCam.transform.position" which tells the Unity3D that FPCam's position is the origin

      Second is "FPCam.transform.forward" which tells the Unity3D that direction is where FPCam's front

      Third is "out hit" which tells the Unity3D to store th out put in hit variable that we defined before the if statment that 's type of "RaycastHit"

      and finally we have maxDistance variable which we defined at the beginning of our code and equals to infinity

      after that we print the tag and then we check if the tag equals to Enemy if so disable the object (reason we used == rather than = is because in programming single = sign means change the value of the variable and == means compare the value to this value) now if we make a cube ad resize it like in the picture and give it a tag of Enemy we should be able shoot it and disable it, but you just 1 isn't enough and it would be nice to see how many you killed and respawn when there are all gone, Let's do it! first put few more and group them inside of an empty game object now we need to change the code a little bit :

      using System.Collections;
      using System.Collections.Generic; using UnityEngine; public class GunScripts : MonoBehaviour { //Assigning Public Variables public Camera FPCam; //Assigining a public variable as a refrence for our player camera public GameObject[] enemyArray; //Assigning private variables private float maxDistance = Mathf.Infinity; //assigning variable for maximum distance that equals infinity private int score = 0; //Assigning a variable for score private int EALength; //Assigning a variable for the length of the enemy array //Start Method runs before the first frame update private void Start() { EALength = enemyArray.Length; //Sets the EALength variable to the lenght of the enemyArray } private void Shoot() //Creating a new method for shootng { RaycastHit hit; //Assigning a variable for the Raycast out put if(Physics.Raycast(FPCam.transform.position, FPCam.transform.forward, out hit, maxDistance)) //Check if the Raycast hit anything if so execute the code in the if statement if false do nothing { print(hit.transform.tag); //Print the tag of the the object that the Raycast hit udeful for debugging if(hit.transform.tag == "Enemy") //Checks if the object's tag is "Enemy" if so execute the following comments if false do nothing { hit.transform.gameObject.SetActive(false); //Disables the object score ++; //add 1 to the "score" variable EALength --; //Subtrats 1 from EALenght variable } if(EALength == 0) //if EALenght equals 0 execute following if not { Invoke("respawner", 1); //Invoke(Call) respawner with a delay of 1 second } } } // Update is called once per frame void Update () { if(Input.GetButtonDown("Fire1")) //Checks if the left mouse button pressed { Shoot(); //call the Shoot() method } } //creating a method for respawning the the enmys private void respawner() { for(int i = 0; i < enemyArray.Length; i++) //A for loop that will count to the enemyArray length and executes the code evry step { enemyArray[i].gameObject.SetActive(true); //Activates every enemy by getting the i variable from the for loop and using it as the Array index number } EALength = enemyArray.Length; //Resets the value to number of enemy in the scene } }

      Great! That's exactly what we want! now let's put a text UI Element in the next step!

      Step 10: Creating a Score Count

      Now we have the Score variable but there is no way we can see, So Let's just do that! Now go to the hierarchy and pres Create>UI>Text it will appear at center of the screen Let's fix it by clicking the text element in hierarchy and press Square in the Rect Transform and press the upper left while pressing SHIFT + ALT (See The Picture)

      now Erase the text in that and change the color to something more readable like light gray now we have to edit the script again :

      using System.Collections;
      using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GunScripts : MonoBehaviour { //Assigning Public Variables public Camera FPCam; //Assigining a public variable as a reference for our player camera public GameObject[] enemyArray; //Making a array for the enemy public Text scoreCount; //Text Variable for scoreCount //Assigning private variables private float maxDistance = Mathf.Infinity; //assigning variable for maximum distance that equals infinity private int score = 0; //Assigning a variable for score private int EALength; //Assigning a variable for the length of the enemy array //Start Method runs before the first frame update private void Start() { scoreCounter(); EALength = enemyArray.Length; //Sets the EALength variable to the length of the enemyArray } private void Shoot() //Creating a new method for shooting { RaycastHit hit; //Assigning a variable for the Raycast out put if(Physics.Raycast(FPCam.transform.position, FPCam.transform.forward, out hit, maxDistance)) //Check if the Raycast hit anything if so execute the code in the if statement if false do nothing { print(hit.transform.tag); //Print the tag of the the object that the Raycast hit udeful for debugging if(hit.transform.tag == "Enemy") //Checks if the object's tag is "Enemy" if so execute the following comments if false do nothing { hit.transform.gameObject.SetActive(false); //Disables the object score ++; //add 1 to the "score" variable EALength --; //Subtrats 1 from EALenght variable } if(EALength == 0) //if EALenght equals 0 execute following if not { Invoke("respawner", 1); //Invoke(Call) respawner with a delay of 1 second } } } // Update is called once per frame void Update () { scoreCounter(); if(Input.GetButtonDown("Fire1")) //Checks if the left mouse button pressed { Shoot(); //call the Shoot() method } } //creating a method for respawning the the enmys private void respawner() { for(int i = 0; i < enemyArray.Length; i++) //A for loop that will count to the enemyArray length and executes the code evry step { enemyArray[i].gameObject.SetActive(true); //Activates every enemy by getting the i variable from the for loop and using it as the Array index number } EALength = enemyArray.Length; //Resets the value to number of enemy in the scene } //Creating a new method for score private void scoreCounter() { scoreCount.text = "Score: " + score.ToString(); } }

      here we only made new public variable for our text element and a new method to display the score :

      private void scoreCounter()
      { scoreCount.text = "Score: " + score.ToString(); }

      this method called twice first in the Start() Method to initialize the text and in the Update Method so every frame it is updated to the latest value, now go to unity and drag the text element to it's place and start playing! that's it! you made your first game! awesome, ha? but a problem, you can't send it to anybody that doesn't have unity installed in their computer but no problem! in the next step we wil see how to build and compile it to an exe!

      Step 11: Bulding and Compiling

      Now the building is really simple and little bit of change in the code you can build for so many Platforms! but we don't want to get complicated so we just go through the basics.

      to build you project you can go to File>Build Settings choose the platform then press add open scene and hit build and make a new folder and name it and that's it! but if you want to get fancy you can go to the player settings because there is too much settings I can't show all of it but you can find it easily on the Internet, now after that you can get the executable and send it to your friends. Thanks for reading i hope you enjoy if you have any questions you can ask it on the comment and please vote me in First Time Author contest, Goodbye!

      First Time Author Contest

      Participated in the
      First Time Author Contest