How can I Improve my code on creating a Race Course Script in Roblox?

Hello guys I need help on How Can Improve this code. I’m new in scripting on roblox and I’m learning here in Roblox Education Multiple Conditions with Else/If | Roblox Creator Documentation. I just create a Race course from Roblox Challenges. So I experiment on how to Add code so that when players finished, they can repeat the race by touching the start line.

local timePassed = 0
local finishLine = script.Parent
local startline = game.Workspace.startPart

-- Used to keep finish() and timer from repeating when race is over
local raceActive = false

--Start the race when the player touces the start line
local function start()
	raceActive = true
	timePassed = 0
	while raceActive == true do
		wait(1)
		timePassed = timePassed + 1
		print(timePassed)
	end
end

-- Runs when the player touches the finish line and shows them an award
local function finish()
	raceActive = false
	print("You finished in " .. timePassed)

	if timePassed <= 10 then
		print("You get a gold medal!")
	elseif timePassed > 10 and timePassed <= 20 then
		print("You get a silver medal!")
	elseif  timePassed > 20 and timePassed <= 30 then
		print("You get a bronze medal!")
	else
		print("Try again!")
	end
	
end


-- Checks if a player touches the part when a race is active
local function partTouched(otherPart)
	local character = otherPart.Parent
	local humanoid = character:FindFirstChildWhichIsA("Humanoid")
	if humanoid and raceActive == true then
		finish()
	end

end

--Checks if a player touches the part when a race is not active
local function partTouched2(otherPart)
	local character = otherPart.Parent
	local humanoid = character:FindFirstChildWhichIsA("Humanoid")
	if humanoid and raceActive == false then
		start()
	end

end

startline.Touched:Connect(partTouched2)
finishLine.Touched:Connect(partTouched)

You dont need a while loop to count the time.
Do something like this

local timeTracker = {}

local function startTouched(player) 
-- have a check in here to make sure it only does this once
       timeTracker[player.Name] = os.clock()
end

local function endTouched(player)
       local startTime = timeTracker[player.Name]
       If startTime then
          Local totalTime = os.difftime(os.clock, startTime)
          If total time < 10 then
                -- do what ever here
          End
          TimeTracker[player.Name] = nil 
      End

Rnd
3 Likes

Ohh Thank you so much!! It so much easier to code that way.