using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using UnityEngine; using UnityEditor; using UnityEngine.SceneManagement; public class Timing: MonoBehaviour { TimingUI ui; public List sectorTimes; public bool timerEnabled; public string mapName; public double sectorTime; public double lapTime; public Sector[] sectors; double sectorStart; double lapStart; void Awake() { ui = GetComponent(); sectorTimes = new List(); sectorStart = 0.0; sectorTime = 0.0; sectors = GetComponentsInChildren().OrderBy(s => s.sector).ToArray(); // set map name Scene scene = SceneManager.GetActiveScene(); mapName = scene.name; Debug.Log("Track Sector Count - " + sectors.Length); LapStorageService.GetPlayerLaps(mapName); } void Update() { if (timerEnabled) { sectorTime = Time.timeAsDouble - sectorStart; lapTime = Time.timeAsDouble - lapStart; } } public void StartTimer() { if (sectors.Length == 0) { Debug.LogWarning("No Sectors found in timing"); return; } Debug.Log("Started Timer"); timerEnabled = true; lapStart = Time.timeAsDouble; sectorStart = Time.timeAsDouble; } public void StopTimer() { sectorTimes = new List(); timerEnabled = false; sectorTime = 0; lapTime = 0; Debug.Log("Timer Stopped"); } public void NextSector(int sector) { if (!timerEnabled) return; // they turned around or somethin? if (sectorTimes.Any(s => s.Sector == sector)) return; // this basically makes sure the timer doesn't do anything weird // due to respawns, driving in the wrong direction etc // you have to hit the sectors in numbered order // --------------- // make sure sectors are only accessible by being hit by following // the track correctly! if (sector != sectorTimes.Count + 1) return; double sTime = Time.timeAsDouble - sectorStart; SectorTime s = new SectorTime { Sector = sector, Seconds = sTime }; sectorTimes.Add(s); sectorStart = Time.timeAsDouble; Debug.Log($"{sectorTimes.Count} / {sectors.Length}"); if (sectorTimes.Count == sectors.Length) { EndLap(); NextLap(); } } void NextLap() { sectorTimes = new List(); StartTimer(); } public void EndLap() { // when live reloading this happens if (sectorTimes == null) Awake(); Debug.Log($"Ending lap Sectors={sectorTimes.Count} Name={mapName}"); Lap l = new Lap { Map = mapName, Sectors = sectorTimes }; Debug.Log($"EndLap {l}"); LapStorageService.PersistLap(l); StartCoroutine(RecentLapLifecycle(l)); } IEnumerator RecentLapLifecycle(Lap l) { ui.ShowRecentLap(l); yield return new WaitForSeconds(3); ui.HideRecentLap(); } public Lap PB() { return LapStorageService.PB(mapName); } public double PBSectorDiff(SectorTime s) => PB() switch { Lap pb => pb.Sectors.SingleOrDefault(fls => fls.Sector == s.Sector) switch { SectorTime fastestSector => s.Seconds - fastestSector.Seconds, null => -1d, }, null => -1d, }; public double PBLapDiff(Lap lap) => PB() switch { Lap pb => lap.TotalTime() - pb.TotalTime(), null => -1d, }; }