Touched Function Not Working

So I’m trying to make a simple race system that does the following. It will start counting up in increments of 0.1 seconds, and will stop as soon as something touches it, then printing the time between when the count started and when the part touches it. I can’t seem to make it work; I’m new to touched events. Here’s my script:

local ReplicatedStorage = game:GetService("ReplicatedStorage")

local FinishLine = game.Workspace["Racing System"].FinishLine
local lapTime = ReplicatedStorage:WaitForChild("lapTime")

local function StartEnd()
	while FinishLine.Touched == false
	do
		lapTime = lapTime + 0.1
		if FinishLine.Touched == true
		then
			print("Your Time Is: " .. lapTime)
			break
		else
			wait(0.01)
			print(lapTime)
		end
	end
end

FinishLine.Touched:Connect(StartEnd)

Any help is appreciated, thanks!

2 Likes

There’s multiple things that could make this not work, first off check if the function is even working (Put a print below the local function line). If it doesn’t work then most likely something is wrong with the part connected to the Touched function. If all that works then most likely its something wrong with the while FinishLine.Touched == false do line. To fix this and overall improve this I would probably completely remove the while true do loop. Outside of the function you should have a loop or something similar to increase their lap time. This could be done with a table with players in it or in a script inside of each player or whatever you want to do. If the finish line is touched then the player would either be excluded from gaining laptime from within the table or the loop inside the player would stop.

Instead of doing “lapTime = lapTime + 0.1” do lapTime.Value = lapTime.Value + 0.1

And also change that where you access it in other places in the script.

1 Like

The compound assignment operators were recently added, so just do

lapTime.Value += 1

if it’s a variable with no property named value, just do

lapTime += 1

@MJTFreeTime


i have also noticed some errors.

This won’t ever fire as this is inside a function that should take place when a brick is touched. Therefore is cannot fire like i have said. If the brick has to be touched in order for the if touched == false to run, it can never run, because the if statement can only run when the brick is touched.

The function isn’t really necessary there, so remove the function and event.

1 Like

FinishLine.Touched is an event, so you’re essentially checking if an event is equal to a boolean, which is false, and therefore the condition isn’t met for the loop, so of course it won’t work.

1 Like