Tuesday, December 7, 2021

Move your player using keyboard key(A,D,S,W)

Move your player using keyboard key

First create a player to which you want to move. See Below here i have taken a cube to which i will move using keyboard keys.(A,D,S,W).


 
Now Add cube in your game scene.
Select your player(here cube) and give it some height.
Here I have given Y=3 (set position Y=3 in Transform).


Now Time to add a c# script to your player.

for this Go to Assets right click select create and again select c#script. Give it some name whatever you want , here i have given playermove.

Left:    A
Right:    D
Up:    W
Down:    S
UpArrow :    forward
DownArrow :    Back

Playermove.cs

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

public class Playerove : MonoBehaviour
{
    public float speed = 5.0f;
    void Update()
    {
        if(Input.GetKey(KeyCode.A))
        {
            transform.position += Vector3.left * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.D))
        {
            transform.position += Vector3.right * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.W))
        {
            transform.position += Vector3.up * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.S))
        {
            transform.position += Vector3.down * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.UpArrow))
        {
            transform.position += Vector3.forward * speed * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            transform.position += Vector3.back * speed * Time.deltaTime;
        }
    }
}

Attach this Playermove.cs script to your player. 
and its all done! 

See the video how it will look in game mode:

Other Script Which you can use to move player:
Left:    A
Right:    D
Up:    W
Down:    S
UpArrow :    forward
DownArrow :    Back

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

public class Playerove : MonoBehaviour
{
    public float speed = 5.0f;
    void Update()
    {
            if (Input.GetKey(KeyCode.A))
            {
                transform.Translate(-0.1f, 0f, 0f);
            }
            if (Input.GetKey(KeyCode.D))
            {
                transform.Translate(0.1f, 0f, 0f);
            }
            if (Input.GetKey(KeyCode.S))
            {
                transform.Translate(0.0f, -0.1f, 0.0f);
            }
            if (Input.GetKey(KeyCode.W))
            {
                transform.Translate(0.0f, 0.1f, 0.0f);
            }
            if (Input.GetKey(KeyCode.UpArrow))
            {
                transform.Translate(0.0f, 0.0f,0.1f);
            }
            if (Input.GetKey(KeyCode.DownArrow))
            {
                transform.Translate(0.0f, 0.0f, -0.1f);
            }
    }
    }

We have one more way to move our player in Horizontal and Vertical direction : By using GetAxis!
See the Script below and attach it to your player.

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

public class Playerove : MonoBehaviour
{
    public float speed = 5.0f;
    Vector3 Vec;
    void Update()
    {
        Vec = transform.localPosition;
        Vec.x += Input.GetAxis("Horizontal") * Time.deltaTime * speed;
        Vec.z += Input.GetAxis("Vertical") * Time.deltaTime * speed;
        transform.localPosition = Vec;
    }
}




 






Tuesday, August 17, 2021

How to apply texture on an object

Hello friends , today we will see how we can apply any desired texture on an object.

Here I will take some objects and apply different type of texture on to them.

So first place your Object into the game scene like below.(Here I have taken 3D objects like cube, sphere, Capsule and cylinder)


Now we can download Texture Images from the google which we want to apply on to these object.

see below how we can do this:


Download any one image and go to unity create one folder named as Image and import that image to this folder.

new create one material you can give any name to this i will say this wooden_texture.

Select this material and lock it from the inspector then drag the downloaded images to the material albedo, see below:



After doing this you can unlock the material, and you will see your material will get a texture of your image.

To make it more perfect change the shader (see top of the inspector) from standard to Unlit/texture.


now you can drag and drop the material to the object to apply the texture to the object ,

see below:


In the above image you can see we have successfully applied the wooden texture on to our cube object.

similarly I have applied fire, sky , and wall texture to the objects .

see how it looks after applying the texture on to to objects.



now I will tell you the simplest way to apply a texture onto object ,

simply drag your texture image onto the object and you will see automatically one material folder will be created and inside that folder your image texture material will be present.


I have attached a rotate script to all objects see how it looks:



Used Rotate Script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class Rotate : MonoBehaviour

{

    public float speed = 15.0f;

    void Update()

    {

        transform.Rotate(0, 1*Time.deltaTime*speed, 0);

    }

}


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. :-)