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

How do I fire a function when someone walks near a part?

2 answers

✓ Accepted answer

This should work for you. (Apologies for the complexity.)

NOTE: I goofed this at first (The inequality symbols were swapped (>= instead of <= and < instead of >). This should be fixed.

EDIT: this won't detect when the player leaves the radius wat? currently trying to fix

EDIT EDIT: Found out why it wouldn't work and fixed it; I was stupid enough to forget that variables connected to properties don't change when the corresponding property changes.

--[[
	This code will cause the code to fire whenever the player is 100 studs away from the part.
	It will then only fire again if the player has left the radius before re-entrance.
]]
local used = false -- we'll need this 
local BindableEvent = workspace.BindableEvent

wait(5)
while true do
	for _, player in pairs(game:GetService("Players"):GetPlayers()) do
		local distance = player:DistanceFromCharacter(script.Parent.Position) -- set up the distance
		local updateDistance = coroutine.create(function() -- this was the solution to the bug
			while true do -- y'know
				distance = player:DistanceFromCharacter(script.Parent.Position) -- update the distance
				wait() -- ayy no overflows here bro
			end
		end)
		coroutine.resume(updateDistance) -- tada issue solved
		if distance <= 100 and not used then -- detect when the player is within a 100-stud field of the part, and then make sure used is false
			used = true -- set used to true
			function() end -- put your function here. function() end is just so that you don't get lost in the code; remove it when you use this
			local HelperCoroutine = coroutine.create(function()-- couroutine to help update the "used" variable when the player leaves the 100-stud field
				while true do
					if distance > 100 then -- when the distance is less than 100 studs (the player left the field)...
						BindableEvent:Fire() -- fire the bindable event we created...
						coroutine.yield() -- we don't need this anymore, so bye thingy
					end
				wait() -- don't wanna overflow with while true do
				end
			end)
			coroutine.resume(HelperCoroutine) -- start up the coroutine
			BindableEvent.Event:Wait()
			used = false -- yey
		end
	end
	wait() -- nope, we ain't overflowin'
end

2 comments

0

Thanks, I appreciate the effort!

0

You're welcome!

I would create a part, make it invisible, and make it go around the part. I would then use it as the sensor.

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