Development Games

Unity3D Tutorial

Introduction to Unity 3D

Unity 3D is a powerful game development engine. It is cross platform that is it allows you to create games for mobile, web, desktop and console, around 30 platforms in all. Unity 3D has many exciting features, a few of them are given below:

  • Cost: Unity 3D’s personal version is free of cost for beginners, students and hobbyists. Unity Personal has all the core features of Unity. It also has core analytics, cloud build, ads, multiplayer, in-app purchases and cross platform features. Other than these features Unity personal has a few limitations too. Two other versions Unity Plus and Unity Pro are also available for serious creators and professionals, starting at the price of $35 per month.
  • All In-one Editor: Unity is known as an all in one editor. The Unity editor has multiple artist friendly tools for designing impressive experiences. It has a strong suit of developer tools for implementing game logic and high end performing gameplay. Unity also allows you to create both 2D and 3D games. It also includes AI pathfinding tools based on a navigation system. It has an excellent built-in system to create eye catching user interfaces. Its Box2D physics engine allows us to create realistic motion, momentum, force and gameplay.
  • Platforms: Unity supports many different platforms like Linux, IOS, Android, Windows, etc. totally nearly 30 platforms.
  • Virtual and Augmented Reality: Unity supports for virtual and augmented reality development. It is most widely used engine for XR development. It has Microsoft HoloLens, Stream VR/Vive, Gear VR and PlayStation VR support in Unity Plus for virtual and augmented reality.
  • Multiplayer: For real time networked and multiplayer games Unity is the best option. It provides servers for real time collaboration.
  • Engine Performance: Unity’s engine performance is extraordinary. Multi-threaded compute system is coming for intensive scenarios. Unity engine has advanced profiling tools which determines if your game is CPU bound or not and also tells how to optimize it with better experience.
  • Unity Asset Store: It is a massive catalog of free and paid content. You can increase your development time by downloading many built-in free models and assets. Even Unity asset store has complete projects both for free and paid.
  • Graphics Rendering: Unity has one of the best graphics rendering system. It allows you to create environments like luminous day, gaudy glow of neon signs, dimly lit midnights and shadowy tunnels. It produces amazing visual effects. Although Unity supports multi-platform but still it tries to cover low level graphics API of every platform for better results and smother user experience.
  • Team Collaboration: It has features that enable collaboration and simple workflow. Unity’s cloud storage allows you to save, share and sync your projects anywhere.
  • Performance Reporting: Unity performance reporting system deals with issues in real time. High priorities issues are solved very efficiently. Finds application errors across devices and platforms.

Unity Interfaces

Let’s explore Unity editor’s interfaces, which are configurable.  It is made up of tapped windows that you can rearrange according to your need.  Let’s explore the default window settings. Here is the image how it looks

unity 3d environment

Hierarchy Window

The Hierarchy window represents every object in the scene. It shows how objects are linked with each other in the scene, so these two windows are related. In hierarchy window there is a drop down list named as Create. You can create an empty object, 3D objects, 2D objects, light, audio, video, particle system and camera objects very easily. The hierarchy window is shown below. ‘Untitled’ is the name of the scene. You can rename it as you want. You can see a drop down icon at the very right side of untitled (scene name). By clicking on this drop down you can see different options for Save Scene and Add New Scene.

Unity3D Hierarchy Window

Scene Window

Scene window is where you create your scene. It is where you can interact with your game objects and models. You can resize, reshape and reposition your scene objects. This is the window where you start working with Unity. Scene view can be 2D or 3D depending on the setting of your project. Here is a screen shot of how the scene window looks:

Unity3D Scene Window

In scene window you can see another tab labeled Shaded, this is where you can select what type of view you want either shaded or wireframe. It has many other options like Miscellaneous, Global illumination, Real time GI, Baked GI and many others. You can view to 2D or 3D by using the button next to the Shaded drop down. Next is the toggle button for scene lighting. Similarly a toggle button for scene audio. Next is a drop down list to enable sky box, fog, animated material and image effects.

Game Window

Game window represents your final, published game in play mode. It is rendered from the cameras you used in your game. In game window you can see another tool bar as shown below in the screen shot:

Unity3D Game Window

Display 1 shows camera present in your game scene. By default it is set to Display 1 for main camera. If you have multiple cameras and you want to switch then you can select from drop down list. Next to this you can see a drop down for aspect ratios. You can select according to your target device monitor screen. Next you can see a Scale slider to zoom in. Scroll to the right and examine more details of your scene in play mode. Next is the button for Maximize On Play, when clicked, the game window size will be maximum on play mode. Mute Audio toggle is used for mute/unmute audio. Stats shows rendering statistics about your game’s audio and graphics.

Project Assets Window

As the name shows assets window has all the assets of your project which you can use. If you import something new it will appear in project assets window. Project asset window has two parts, the left panel and right panel as shown in the below screen shot:

unity3d simple1

Left pane shows the hierarchical structure of the project’s assets.  When you click on any folder it will show the details in the right panel. For example in the given figure Prefabs folder is clicked in left panel so its details are showing in the right panel as it contains two game objects. In the left panel you can see a Favorites section, where you can drag items which you want to use very frequently to avoid time waste in searching for them. Above it you can see a Create drop down which enables you to create a C# script, a folder, a shader, a GUI skin, a scene, a prefab, a material and much more.

Console Window

Console window is the place where you can see your errors, warnings and messages. You can adjust them by clicking their toggle buttons. It also allows you to clear all the errors, warnings and messages. You can pause errors for a certain time. Here you can see in the following figure

Unity3d console window

The drop down icon at the very top right corner has options for Editor Log and Stack Trace Logging.

Inspector Window

Inspector window is one of the most interesting and useful window of the editor. It is the place where you can edit all the properties of the selected game object. Every game object has its own type so their properties will be different and inspector’s window can vary. Assets, scripts and game objects all vary in properties. Lets see the properties of a cube in inspector window. Here is the image:

Unity3D Inspector Window

You can rename your game object by just clicking on the previous name and typing a new one. Next you will see the transform section where you can adjust position, rotation and scaling of your selected game object. In the last you see a button name as Add Component, click on it to add new components to your game object, for example if you want to attach a script, just click on add component and type your script name.

Tool Bar

Last is the tool bar tab, it has many useful features. It contains some basic tools for manipulating the scene view and objects. In center there are buttons for play, pause and step control. The next two buttons shows your Unity cloud and Unity account. Here is the figure how it looks:

unity3d toolbar

Getting Started With Unity

Let’s start creating a new project in Unity because it’s time to play with what we have learned. Double click on Unity icon following window will appear:

Unity3d Project Screen

Enter Project Name, select a workplace Location and then select type of your project either 2D or 3D. Click on Create Project.

By default you will see an untitled scene containing a main camera and directional light in the scene. Let’s start creating an environment.

Building Environment

First of all create a plane by clicking on Create -> 3D Object and then select Plane. Or alternatively you can create it by clicking on GameObject -> Game Object and then select Plane. Go to hierarchy window and click on plane game object. Now go to inspector window and rename it as Ground. Now adjust transformation values so that this plane looks like a straight road. Just scale X to 6 and Z to 50. Here is the image how it looks

Unity3d Inspector Window

Now download a road texture and apply it on the ground object. Create a folder name as Texture. Drag downloaded road texture to Texture’s folder. Now select Ground and drag road texture in the scene view. Here is the image how it looks

Unity3D Road

This is the texture I downloaded

Unity3D Road

After applying texture on the ground, click on Ground and set tiling in inspector window. Here is how I set it.

Unity3D Settings

Now you have created a road model, let’s create a ball model in unity.

Go to Create -> 3D object and then select Sphere, you will see a sphere object in scene window. Select it and go to the inspector window to rename it as Ball. Now adjust transformation values accordingly. Just scale it to 5 along all three axis and reposition it to the center of the road. Here is how it looks

Unity3D Ball on Road

Now create a fence or wall around the road.

Go to Create -> 3D Object and then select Cube. Select it and rename it to Wall1. Go to inspector window and set transformation values so that it looks like a wall around the road. Here is how it looks:

Unity3D Inspector Window

See these transformation values for Wall1. Scale Y to 6 and Z to 500. Then adjust its position so that it comes at the corners of road.

Unity3D Properties Window

Now search for a wall texture download it and copy to the Texture folder in assets. Drag wall texture to the wall in the scene window. Adjust tilling so that it looks nice and smooth. I adjusted tiling as X to 50 and Y to 1.5. After adjusting tiling this is how it looks

Unity3D Road

This is the texture I used for wall

Unity3D Wall

We have created wall for one side of the road. Now do the same thing for the other side of the road too. Instead of going through the all the process we can just copy Wall1 and rename it to Wall2.

Select Wall1 in hierarchy window and then right click and then select Duplicate option. It will create another game object having same size and transformation values. Click on Wall1(1) and rename it to Wall2. Now adjust position so that it comes to the other corner of the road.

See the following image how cool it looks

Unity3D Red Ball on Road

My position values for Wall2 are X to -29.6 Y to 2.6 and Z to 2.6.

Now create a material for Ball. Go to Project window and create a folder by right clicking on the mouse and then select Folder. Name it as Materials. Again right click on mouse and create a material. Name it as redBall. In inspector’s window select color of material. Go to Main Maps and select Albedo color to red. Increase the metallic texture by scrolling bar to the right. Drag this material to the Ball in the scene view. Here is how it looks

Unity3D Red Ball on Road

Here is how material looks:

unity3d simple2

So we are done with our environment development. Now time to do some coding. For this we have to create a script.

Scripting in Unity

To implement your own gameplay features and to control the behavior of the game Unity provides as a scripting mechanism. You can write your own script for the desired output of the game. With these scripts you can trigger game events, can change component’s properties and you can respond to user inputs. Basically Unity supports two different programming languages for scripting purpose, one is C# and other is JavaScript. Other than these two languages many other .NET languages can also be used with Unity. Scripts are known as behavior component in Unity.

Creating a Script

Let’s start creating a Unity script. For this go to the assets window and create a new folder named Scripts (you can skip creating new folders for every new type of asset but its good practice to keep things organized). Here is how my assets window looks now:

Unity3D Folders

Now open the Scripts folder, right click, then go to Create and select C# script. Rename script to Movement. We are creating this script to move and roll the ball on the road. For now the ball is stationary, doing nothing, let’s create some movement in it.

Double click on the Movement script it will open in Mono Develop. If your script is a mono behavior then you will see some pre written code like this

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

public class MovementScript : MonoBehaviour {

    // Use this for initialization
    void Start () {
        
    }
    
    // Update is called once per frame
    void Update () {
        
    }
}

You can see two functions Start() and Update().

Start(): Start function is used for initializing variables and objects. It is called only once when the script is enabled just before any other update function calls.

Update(): It is a mono behavior function, it is called once in every frame.

Other than these two there are many other mono behavior functions for example awake(), fixedUpdate(), lateUpdate() etc.

To move the ball on the road first of all you have to make it a rigid body (it is an ideal solid body in which deformation is neglected). Select Ball in hierarchy window and click on Add Component button in inspector window. Type rigid body and press Enter. A rigid body will attach to the Ball. Now go to script and create a private variable of type Rigidbody. Now assign rigid body of the Ball to this variable you just created in the script.

private Rigidbody rb; 
rb = GetComponent<Rigidbody> (); 

Now write some code for the movement of this rigid body. What’s the idea? Ball should move when I press arrow keys of the key board. It should move forward when up key is pressed, backward when down key is pressed and so on.

So the input in coming from the keyboard, how should I get this input? Unity’s Input class has a function name GetAxis(), to returns the value of virtual axis identified by the axis name. Create two variables one for x-axis and one for y-axis input. Here is how it should be

float moveHorizontal = Input.GetAxis ("Horizontal");

Now create a Vector3 variable to get movement values.

Vector3 movement = new Vector3 (moveHorizontal, 0.0f,moveVerticle ); 

First parameter is the value of x-axis, second is the value of y-axis and third is the value of z-axis. As ball will not move in the direction of y-axis so assign zero to it. Lastly add this movement to rigid body and multiply with a constant number for speed or create another variable for speed. See the complete code below

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

public class Movement : MonoBehaviour {

    public float speed; 
    private Rigidbody rb;
    // Use this for initialization
    void Start () {
        rb = GetComponent<Rigidbody> ();
    }
    
    // Fixed Update is called after fixed number of frame
    void FixedUpdate () {
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVerticle = Input.GetAxis("Horizontal"); 
        Vector3 movement = new Vector3 (-1*moveHorizontal, 0.0f,-1*moveVerticle );
        rb.AddForce (movement * speed);

    }
}

As speed is a public variable so you can assign value in the inspector window. Attach this script to the ball by dragging it to the inspector window or by pressing Add Component button. Press play button and test your coding either ball is moving or not.

Setting Camera

Last thing you will notice is when you press forward button and ball starts moving it goes out of the camera as camera is stationary. What should we do? We should move camera too? Yes it is the simplest thing to do. Make the camera child of the ball by dragging main camera to the ball.

Conclusion

This was a basic introductory tutorial in which you learned many interesting features, environment building and scripting in Unity. Don’t hesitate, start creating your first game with Unity today and enjoy!

About the author

Admin

A passionate Linux user for personal and professional reasons, always exploring what is new in the world of Linux and sharing with my readers.