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 !!!
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.
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:
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);
}
}
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.
{
}
}
}
0 Comments:
Post a Comment
Thank you for your comment !