Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Timer

Discussion in 'Scripting' started by m_nikolov, Apr 1, 2024.

  1. m_nikolov


    Feb 18, 2024
    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)
  2. zulo3d


    Feb 18, 2023
    Code (CSharp):
    1. using UnityEngine;
    2. public class RaceMaster : MonoBehaviour // place this script on the finish line trigger
    3. {
    4. float raceStartTime;
    5. float raceFinishTime;
    7.     void Update()
    8.     {
    9.         if (Input.GetKeyDown(KeyCode.W) && raceStartTime==0) // Start race?
    10.             raceStartTime=Time.time;
    11.     }
    13.     void OnTriggerEnter(Collider other)
    14.     {
    15.         raceFinishTime=Time.time-raceStartTime;
    16.         other.GetComponent<Rigidbody>().drag=5; // add drag to make the car slow down
    17.         other.GetComponent<CarScript>().enabled=false; // disable car's script so it can't move
    18.     }
    20.     void OnGUI()
    21.     {
    22.         if (raceFinishTime>0)
    23.         {
    24.   ;
    25.             GUI.Box(new Rect(Screen.width/2-200, Screen.height/2-100,400,200),"");
    26.             GUI.Label(new Rect(Screen.width/2-70,Screen.height/2-50,200,50),"Your time: "+raceFinishTime.ToString("f2"));
    27.             if (GUI.Button(new Rect(Screen.width/2-50,Screen.height/2,100,30),"Garage"))
    28.                 Application.LoadLevel("Garage");
    29.         }
    30.     }
    31. }
    Last edited: Apr 1, 2024
    m_nikolov likes this.
  3. m_nikolov


    Feb 18, 2024
    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
  4. m_nikolov


    Feb 18, 2024
    The timer works. Thank you for the help!!!