Hello everyone! Could I have some help?
I’m making a racing game (in 2D), and the car is moving while “W” is pressed. But I want to make a timer, which starts when I first press “W” and stop when the car enter a trigger. (Now, when the car enters a trigger, the race is finished and the car can’t accelerate and slows down the speed (and does not interact with any keys from the keyboard)). And when Trigger is entered, a canvas window is showed, in it there is a button which leads to the garage. Above the button there is a textBox in which is written “Your time:” and next to it there is another textBox, in which the time will be shown. I only want to ask if someone can help me with the script for this all to work. I didn’t attach here any code, because the code for timer is seperated from other scripts (It’s just an seperate Script)
using UnityEngine;
public class RaceMaster : MonoBehaviour // place this script on the finish line trigger
{
float raceStartTime;
float raceFinishTime;
void Update()
{
if (Input.GetKeyDown(KeyCode.W) && raceStartTime==0) // Start race?
raceStartTime=Time.time;
}
void OnTriggerEnter(Collider other)
{
raceFinishTime=Time.time-raceStartTime;
other.GetComponent<Rigidbody>().drag=5; // add drag to make the car slow down
other.GetComponent<CarScript>().enabled=false; // disable car's script so it can't move
}
void OnGUI()
{
if (raceFinishTime>0)
{
GUI.skin.label.fontSize=20;
GUI.Box(new Rect(Screen.width/2-200, Screen.height/2-100,400,200),"");
GUI.Label(new Rect(Screen.width/2-70,Screen.height/2-50,200,50),"Your time: "+raceFinishTime.ToString("f2"));
if (GUI.Button(new Rect(Screen.width/2-50,Screen.height/2,100,30),"Garage"))
Application.LoadLevel("Garage");
}
}
}
1 Like
Thanks, I wanted only for the timer, because everything else in your code was done. It’s my bad, because I wrote “for this all to work”. Sorry for the time you lost writting
The timer works. Thank you for the help!!!