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

0 Comments:

Post a Comment

Thank you for your comment !