Thursday, July 22, 2021

How To Create Score for Your Unity Game

Create C# Script To Count Score For Your Game

Hello Friends, so today we will write score script for our game.For this script, first we will see the score result in the console window and then we will add a text box (in canvas) in game scene view so that we can see the score in the running game as well ,so lets start !!!

Open your unity game/project.

  Here i will open First_Game if you want to make dedicated project for score only go to NEW in top right corner,give name and select path for your project, okay so we give continue with First_Game project. 

first view of this project will be :

 In the above image we can see the car 3d model which we have added earlier.
just for a recap i am adding a simple rotate script to the car here and will add a score for this car rotation.

Rotate_car script is below:

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

public class Rotate_Car : MonoBehaviour
{
    public float speed= 2.0f;
    void Update()
    {
        transform.Rotate(0, 1 * speed * Time.deltaTime,0);
    }
}
 

Rotating car looks like below:

Now we will see the Score script , add an empty game object and name it score_object.Add a c# script and name it Score.
To see this how to add 3D object and C# script search "GameObject in Unity3D" in the search bar you will get the complete process for the same.

Score script is below(attach this script to score_object):

using UnityEngine;
using System;
public class Score : MonoBehaviour
{
    float time = 0;
    int score;

    void Update()
    {
        time += Time.deltaTime;  // here time will be float
        score  = (int)Math.Round(time); // float to int
        Debug.Log(score);
    }
}
 

In below video we can see the Time based score(time in second) in Console Window.

Now we will add Text in our scene view.

For how to place text in the any position in canvas screen , see this simple video.

See the below Score script to see the result in Game view, attach this script to the Text or any game object and follow given steps.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
    float time = 0;
    int score;
    public Text score_text;


    void Update()
    {
        time += Time.deltaTime;
        score  = (int)Math.Round(time);
        try
        {
            score_text.text = " Your Score" + " " + score.ToString();
        }
        catch (NullReferenceException)  // add this else you will get NullReferenceException error.
        {
           
        }
    }
}

 After following all the given steps you will see the score like this in game window:
 
 
Thanks  :-)

Sunday, July 18, 2021

The Unity Asset Store And Importing 3D Charater Model

The Unity Asset Store

From Unity asset store user can download assets like Models,Textures,Material,tools like Terrain,Utilities etc and import it inside the game.

In unity asset store verity of assets are available some of them are paid and some of them are free as well.

Here we will import a free car asset in out game.

Google,Unity asset store and open the first link or directly go to https://assetstore.unity.com/

Note: User can add a dedicated tab for asset store in the project it self by: window->asset store or Press ctrl+9


Now user have to sign in asset store.(if don't have account simply create it , its similar to as you created your Facebook account).

After login you will see screen like below:

 

In Search for assets user can type search assets what he wants.

here we will search for free 3d car.

After choosing pricing and Free assets we will see screen like below:


 

Open any asset ->add to my assets->accept->open in Unity

It will automatically open inside the unity project.


Download and Import in into the project.


After following all the above steps our first 3d model is imported inside the unity project which we can see in assets folder.

To add car in Unity game scene we have to open Prefab folder of the downloaded assets from store.

 

Simply user can drag any car (object) into the game scene.

From Inspector window we can change the Position,Rotation and Scale of car.

So its done for now,we see more on this in upcoming post.

Thank you :-)

Thursday, July 15, 2021

Variable in C# (Unity3D)

Variable in C#

There are different type of variable in C# these are :

Int: values like : 1,2,3,4,5,-1,-2,-3,-4..

Float: values like 1.23, 3.44 , 5.48, 9.32 , -12.34....

in C# for float variable we will use "f" after the number exp:

1.23f, 3.44f, 5.48f etc.

String: exp , "unity3D" , " augmented reality" , "Virtual reality"...

Private Variable: These variable are accessible  in side the class only.So user cant change its value from the inspector panel.

Public variables are those variable which will be visible in game scene view and we can change their value from the inspector panel itself.

See below code

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

public class Cubescript : MonoBehaviour
{
    public int intvalue = 0;
    public float floatvalue = 2.34f;
    public string total = "Value sum : ";
    float sum = 0,privatesum = 0;
    private int privateintvalue = 10;
    private float privatefloatvalue = 10.12f;
    void Start()
    {
        print("Stated !");
    }
    private void Update()
    {
        sum = intvalue + floatvalue;
        Debug.Log("Public var : -- "+total+" : "+sum);
        privatesum = privateintvalue + privatefloatvalue;
        Debug.Log("Private var : -- " + privatesum);
    }
}

Implementation in Unity:

in above image of cube inspector panel we can see in Cubescript , Public variables Intvalue, Floatvalue, and Total are shown here(Here we can change these value from inspector).


In Console Window we can see the result for above script.

Public variable : sum of intvalue and floatvalue, see the inspector panel.

Private variable : 2.34 is the sum of privateintvalue and privatefloatvalue, see the above c# script.

now we will change the value for public variable shown in inspector panel through inspector panel itself and see the result:


 In above image we can see , we have changed the value of intvalue to 10 from 0 , Floatvalue to 15.5 from 2.34 and Total (String value) to total from Value sum.

After changing these values we got this result, see below:


After changing the public variable from the inspector we can see the result in console window for above script.

Public variable : sum of intvalue and floatvalue, see the inspector panel.

Private variable : --  20.12 is the sum of privateintvalue and privatefloatvalue, see the above c# script.

 

Thank you :-)


 

Tuesday, July 13, 2021

First Script in C# Unity3D (Rotate Object About Any Axis)


Hello friends , So now its time to write your first script in C# unity3D.

Before write your C# script , make sure that camera , directional light should be in there your scene.

first add an object in the scene on which you will add the script to perform some action.

so here i will add 3d object cube (see below).

If you want to zoom object select it on scene and press "F" on the keyboard.

how to add script into the object?

To make your project user friendly first make a folder named as : Script

Right click in assets window  -> create ->folder (name it Script)


Open Script folder ->create->C# Script ->Cubescript ( give any name to your script)

Other way to add script:

select game object to which you want to add script , in the inspector panel see add component and click it -> write script name (Cubescript), to attach the script to that object.

script extension would be ."cs".

Now open the Cubescript in Visual Studio to edit it.

first look for the script would be like below:


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

Above three lines are the libraries having full of mini function.

The above code shown in the above image is a by default code for any script.

void Start() function is the function which will be called for very first frame in any game/application at run time.

Every script starts wit this function.

void Update() function is the function which will be called for every frame in the game/application at run time. ( 60 frames per second)

code start from Public class Cubescript : MonoBehaviour 

MonoBehaviour is the additional library for mono develop software which unity understands.

Code blocks begins with open curly bracket " { " and end with close curly bracket " } "


1st button is for play the game scene.

2nd button is for pause and play.

3rd button is far play the game scene frame by frame (one by one).

see below code:

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

public class Cubescript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Game Started !"); // run for only first frame
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log("Game Updating !!!"); // run for every //frame after first frame
    }
}

attach this script to your object.

Debug.Log is for print any thing which is inside the bracket(like in the code) in Console.

If console is not there you can add it from window -> General -> Console.



If you have done all the things properly as we mentioned above then its time to run your first script.

hit run button and see the output in console tab(see the screenshot).


Congrats! you have successfully run your first C# script.

For every object you can see Position , Rotation and Scale ARE there in Inspector window.



Now we will rotate the cube around x axis (or any axis which you want.)

 In inspector window you can see rotation is there inside the transform. so write:

transform.rotate(x,y,z);

for x, y, z we can give value 1 or 0 , 1 means object will rotate about that axis. 

0 means object will not rotate about that axis.

So rotate about x axis (here x rotation value will change in transform):

transform.Rotate(1, 0, 0);

Complete Code : 

//Object Rotate about X axis
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Cubescript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Game Started !"); // run for only first frame
    }

    // Update is called once per frame
    void Update()
    {
        transform.Rotate(1, 0, 0);
    }
}



 Thank you :-)



Saturday, July 10, 2021

2D And 3D Objects In Unity3D

First view of our project look like below.

If not ! Then you can change your project layout from layout section in window tab.

here my layout is of 2 by 3.


In hierarchy window you can see there are two game object present already. These Game objects are :

i) Camera 

ii) Directional light

Camera 

left hand side we can see the camera, x,y,z axis and camera preview.

Right hand side we can see the inspector window for camera.From inspector window we can change the position, scale, rotation for the camera.

Sometimes we could not see the object presents inside the scene view.To see the object we can change the camera position/Projection /clipping plane near ,far of the camera.

Directional Light

we can add directional light in our game view from the game object tab ->light->directional light. From the inspector window we can change the light , intensity and more for thew directional light.

Okay ! Now we will add a 3D game object in our scene.

Here in unity we have two option to add game object in the scene.

first from the game object tab GameObject->3DObject->select any of the object from the listed objects like cube,sphere,plane,quad etc.

the other option to add 3D game object is quite simple just right click in hierarchy window select 3DObject and then choose any of the object from the list,see below.


 

After adding the cube 3D Object we can see a cube inside the game scene and inspector window for the cube from which we can change the cube properties.

For axis simply understand this:

X is for LEFT and RIGHT

Y is green on , for UP and DOWN 

Z is for FORWARD and BACKWARD

Here  we can see mesh filter and mesh renderer as component of cube.Mesh Renderer is for rendering the mesh like cube , sphere,Capsule, cylinder etc even we can download meshes from the asset store as well and can use it.

If in the Game  lighting is not proper then go to window tab -> lighting settings -> and Check auto Generate(Generate lighting).

Similarly  we can add other game object like sphere , cylinder , capsule etc in side the scene. 

Thursday, July 8, 2021

Important Tab And Field In Unity3D

Menu And Fields In Unity3D

Before we start our First_Game, we will have a look into some basic and important tab and field present in the unity3D.


1. File

2. Edit

3. Assets 

4. GameObject

5. Component 

6. Window

7. Help

File:


By file , we can create new scene in our project or we can open and add already existed scene inside to our project.

by this we can a project which is already present and we can save our performed task and project.(crl+s)

we can change the build and player setting from the file  option.

After completion  of the project we can make application file of the project by build and run option presents inside the file tab. 

by this file we can install our application created by unity in any of the system.

Edit:

  

By edit we can change the project settings , preferences and also objects and prefabs created in the project (we will discuss about object and prefabs in later posts).

Assets:


By Assets, we can create assets inside the unity. Here we can import assets from our local system our from assets store (custom package).

We can download assets like 3d model, prefabs , terrains etc. from assets store or from anywhere else and can import it to our project.

we can also export the assets presents in the project.

many excited things will be there inside this which we will learn slowly in AR - VR section(so stay tune !) 

GameObject


By GameObject, we can create 2d objects like Sprite , Sprite Mask etc and 3d objects like Cube ,Sphere ,Capsule ,Plane ,Quad ,Text) game object for our project.We can create an empty object as well just by selecting create empty.

Here we can add effects  like Particle effect, Trailing, Line.

Light (Game Object): By this we can add directional light , area light , point light etc. in our project scene.

UI: By this we can add image , button , canvas , text , slider , scrollbar etc in out scene.

We can add audio and video fie from game object.(fore this we will add audio / video source from the component , don't worry we will see example for this a well). 

Component


By this we can add component to our game object.Component like audio / video source, collision collider component , rigidbody , rigidbody2D, Physics, script, UI etc. 

Window


By this we can change the layout of our scene to 2 by 3,4 split,Tall ,Wide

,or to default it self( its better to try it yourself and see the differences among all).

We can add window like game,console,Hierarchy inspector.

By this tab we can add assets store as well.By assets store we can find our useful assets, download it and can import it in our project.

During the uses of MRTK(Mixed reality toolkit) we can use XR settings and Holographic emulation so that we can see the play mode inside the head mounted display like HoloLens.

From this we can change general, animation , audio setting and also light settings through rendering option.

Help


Here we can look into about Unity,Unity Manual.

from help we can check Unity Update,report a bug and can also manage the license.

Thank you !

In the next post we will see the different type of objects and add them into our scene and will perform some task on them. :-)

How To Create Your First Game or Project in Unity3D

Make Your First Game In Unity3D

Hello Friends , as of now we have installed Unity3D. Now its time to create our first unity game!

Here we can create 2D or 3D games and steps to create both are same. 

So ,Finally we go for 3D game, follow the steps:

Step1: Click UnityHub and open it.

Step2: Click NEW


Step3: Select 3D and give some project name .Here i have given First_Game and choose the desired location.

Step4: Click CREATE !

The first view window of your project will look like below:


Now we will see some window and terms which are present in above screen.

In above screenshot there are 4 numbered window.We will look into all one by one.

1. Project and console window

2. Hierarchy window

3. Scene and Game window/view

4. Inspector window


Project and console window

The Project window displays all of the files related to the Project and is the main way by that a user can navigate and find Assets and other Project files in the application.

When user start a new Project by default it will be open. 

If you can't see the any of window then you can add it by following steps show below in the image. 

 

Hierarchy window

The Hierarchy window displays every GameObject in a Scene, such as models, Cameras, or Prefabs.

User can use the Hierarchy window to sort and group the GameObjects you use in a Scene. When user add or remove GameObjects in the Scene view, he also add or remove them from the Hierarchy window.

The Hierarchy window can also contain other Scenes, with each Scene
containing their own GameObjects.

Scene and Game window/view

The Scene view is the interactive window/view into the project/game you are creating.

You can use the Scene view to select and position Object,characters, Cameras, lights, and all other GameObjects.

The Game view is rendered from the single or multiple cameras in your project. It represents the final and published project/game. You need to use one or more Cameras to control what the player sees when they are using your project/game or final application.

Inspector window 

Inspector window is basically used to view and edit properties of GameObjects,Unity components, Assets, Materials,and settings for almost everything in the Unity Editor.

    We will know more about these windows in upcoming post.In next post we will continue with the project First_Game.

Tuesday, July 6, 2021

UNITY3D

Unity3D ?

World's most popular cross platform 3D game engine.

Unity3D has a user friendly development environment.

By unity3D user can creates 2D, 3D games, perform simulations and make applications for Mobile , PC , consoles and Web.

Unity3D comes loaded with some tools and features these tools and features are helpful for both programmer and artist.

For the platform itself unity was built in C++ and over the year it gets optimize for the performance.


Unity3D Installation 

Unity3D installation is quite easy. initially user can install the beta version of unity3d and its free. Letter on user can go for the Pro one. Unity pro has more number of features and facilities for user.

Okay ! So now we will go for the installation of beta version of unity3D.

 Step1: go to  https://unity.com/ 


 Step2: Click Get Started.

 

 Step3: Click Individual.

 

Step4: Click Personal  Get Started.

Step5: Click First time user : Start Here.

 

Step 6:Click Agree and Download.

 

Step7:Downloaded file will be : Unityhubsetup.exe

  

Step8:Double click on Unityhubsetup.exe , choose location and install it.

Step9:Check run unity hub and Click Finish.

Step10:In Unity hub click on install tab and then Add.

  

Step11:Select Unity 2020.3.13f1 (LTS) or the latest version of unity.


Step12: Click next.

Step13:Add Modules like Microsoft Visual studio(Dev tool), and Platforms.(shown in the image)

 


Step14:Check and agree term and condition click next.

Step15:Check and Agree the Android SDK and NDK License.

Step16:Click done and allow Unity to make changes to your device , click yes.

Step17:and its done , Congratulations ! Now your Unity installation has been done.