I’ve been working on a Lap timer and I’m nearly there but I’ve got one minor fault in the code that I’d like help with.
I’ve got a trigger on the start finish line and it’s all working as it should be expect for the fact that the “Best Lap” time is being updated to match the “Last lap” time if the car is taking longer than the recorded “Best”.
To try and illustrate:
Lap 1 time = 1:00
Lap 2 time = 0.50
upto this point it’s working well (I think)
Lap 3 time = 0.70
Lap 4 > 0.70
when the current lap time is greater than the best recorded so far it changes the best to equal the last lap time.
I’m really quite new to coding and so any help would be much appreciated.
private var startTimer;
private var Timer : int;
private var roundedTimer : int;
private var Current;
private var displaySeconds : int;
private var displayMinutes : int;
private var Last;
private var LastMinutes : int;
private var LastSeconds : int;
private var Best;
private var BestMinutes : int;
private var BestSeconds : int;
private var Lastlap;
var font : Font;
function OnTriggerExit(car : Collider)
{
startTimer = Time.time;
}
function OnTriggerEnter(car : Collider)
{
LastMinutes = displayMinutes;
LastSeconds = displaySeconds;
Lastlap = ((LastMinutes*60) + LastSeconds);
}
function OnGUI ()
{
//make sure that your time is based on when this script was first called
//instead of when your game started
var currentTime = Time.time - startTimer;
Timer = currentTime;
//display the timer
roundedTimer = Mathf.CeilToInt(Timer);
displaySeconds = roundedTimer % 60;
displayMinutes = roundedTimer / 60;
Current = String.Format ("{0:00}:{1:00}", displayMinutes, displaySeconds);
GUI.BeginGroup (Rect (540,10,200,200));
GUI.skin.font = font;
GUI.contentColor = Color.black;
GUI.Label (Rect (0, 0, 150, 50), "Current Lap:" +(Current));
GUI.EndGroup ();
Last = String.Format("{0:00}:{1:00}", LastMinutes, LastSeconds);
GUI.BeginGroup (Rect (540,10,200,200));
GUI.skin.font = font;
GUI.contentColor = Color.black;
GUI.Label (Rect (0, 20, 150, 50), "Last Lap:" +(Last));
GUI.EndGroup ();
if (Lastlap < roundedTimer)
{
BestMinutes = LastMinutes;
BestSeconds = LastSeconds;
}
else if (Lastlap > roundedTimer)
{
BestMinutes = BestMinutes;
BestSeconds = BestSeconds;
}
Best = String.Format("{0:00}:{1:00}", BestMinutes, BestSeconds);
GUI.BeginGroup (Rect (540,10,200,200));
GUI.skin.font = font;
GUI.contentColor = Color.black;
GUI.Label (Rect (0, 40, 150, 50), "Best Lap:" +(Best));
GUI.EndGroup ();
}
You’ll notice I’ve got a bit saying else if (X > Y) B = B; I’m trying to say leave B as it is i.e. do nothing but when I changed the code to use what I say someone else was using as s ‘do nothing’ command i.e. return; it seemed to do nothing but actually scrapped it. As I said, I learning as I go along here and so please excuse any noob mistakes.
Thanks in advance.