Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I can't figure out why my OnTouched function won't work? Please Help! Thanks in Advance!

I have a bike and I set up animations and everything. Now what I want to do is up their stats based on how long they stay on the bike. I had my leaderstats script create the IntValues and everything to store how long they have to stay on the bike to up their stats. Next I made this local script inside the seat on the bike. I can't seem to figure out why it won't work though. Thanks in Advance!

local plr = game.Players.LocalPlayer
local plrwork = workspace:WaitForChild(plr.Name)
local char = plrwork:WaitForChild('Character')
local hum = hum:WaitForChild('Humanoid')
local waittimeFold = plr:WaitForChild("WaitTime")
local waittime = waittimeFold:WaitForChild("WaitTimeSpd")
local loop

local function OnTouch(part)
	loop = true
	while loop == true do
		wait(waittime.Value)
		hum.WalkSpeed = hum.WalkSpeed + .2
		waittime.Value = waittime.Value + 1
	end
end

local function EndTouch()
	loop = false
	


script.Parent.Touched:Connect(OnTouch)
script.Parent.TouchEnded:Connect(EndTouch)

4 comments

0

At line 09 Does 'part' have to be a variable? idk try making a variable for part if it doesnt work then change it back if you want.

0

IMO use a regular script if it’s going to be inside the part (bike)

0

ok

0

If I make it a a script I can't locate the player

1 answer

✓ Accepted answer

Server Script under the Bike Part

local loop = true
local debounce = true

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local hum = char:WaitForChild("Humanoid")
		local waittimeFold = plr:WaitForChild("WaitTime")
		local waittime = waittimeFold:WaitForChild("WaitTimeSpd")
		
		script.Parent.Touched:Connect(function(hit)
			if debounce == false then return end
			debounce = false
			if hit.Parent.Name == plr.Name then
				loop = true
				repeat
					wait(waittime.Value)
					hum.WalkSpeed = hum.WalkSpeed + .2
					waittime.Value = waittime.Value + 1
				until loop == false
			end
			debounce = true
		end)
		
		script.Parent.TouchEnded:Connect(function(hit)
			if hit.Parent.Name == plr.Name then
				loop = false
			end
		end)
	end)
end)

The debounce is used to prevent the .Touched Event from firing multiple times

By using the PlayerAdded --> CharacterAdded set-up, we can get the character of a player in order to have checks that the .Touched /.TouchEnded Events are only occurring for that player (so if another player touches the bike, it won't stop)

Make sure to complete your "end" for the .TouchEnded Event

From your previous script, when you check for "plrwork" that would result in giving you the player's character, so you wouldn't need the local char variable

This discussion is preserved as it was. New answers, comments, and votes are closed.