I want to detect when the player is inside of a specific part

I want to detect when the player is inside of the part this script is in so I can set certain values when they enter it and then change them back once they leave it.

Script
function Touch (hit)
	wait()
	if hit.Parent.Name ~= "Rat" and hit.Parent.Name ~= "Office Key" then
		script.Parent.Parent.Active.Value = true
		game:GetService("SoundService").Ambience.PlaybackSpeed = 0.9
		game:GetService("SoundService").Ambience.Volume = 0.035
	end
end

function NoTouch (hit)
	wait()
	if hit.Parent.Name ~= "Rat" and hit.Parent.Name ~= "Office Key" then
		script.Parent.Parent.Active.Value = false
		game:GetService("SoundService").Ambience.PlaybackSpeed = 0.8
		game:GetService("SoundService").Ambience.Volume = 0.02
	end
end

script.Parent.Touched:Connect(Touch)
script.Parent.TouchEnded:Connect(NoTouch)

It will run and properly set the values but will rapidly switch between the Touch and NoTouch functions. I’m stuck now and all my solutions have failed so any help would be appreciated.

Making a region script is pretty hard by hand. I suggest going over ZonePlus V2 since this module can do the work a lot easier.

1 Like

You do not have to use Region3’s or Rotated Region3’s at all. The Touch and TouchEnded approach should work fine, but you will have to memorize what touching parts belong to which player. That is why your code does not work.

1 Like

.Touched and .TouchEnded are pretty bad for this. I have tried, but no good result.

Thank you! Worked perfectly after adding that check and removing the ‘wait’ in each function.

For anyone wondering what the code looks like now.
local name = nil

function Touch (hit)
	if hit.Parent.Name ~= "Rat" and hit.Parent.Name ~= "Office Key" and hit.Parent:FindFirstChild("Humanoid") and name == nil then
		script.Parent.Parent.Active.Value = true
		name = hit.Parent.Name
		game:GetService("SoundService").Ambience.PlaybackSpeed = 0.9
		game:GetService("SoundService").Ambience.Volume = 0.035
	end
end

function NoTouch (hit)
	if hit.Parent.Name ~= "Rat" and hit.Parent.Name ~= "Office Key" and hit.Parent:FindFirstChild("Humanoid") and name == hit.Parent.Name then
		script.Parent.Parent.Active.Value = false
		name = nil
		game:GetService("SoundService").Ambience.PlaybackSpeed = 0.8
		game:GetService("SoundService").Ambience.Volume = 0.02
	end
end

script.Parent.Touched:Connect(Touch)
script.Parent.TouchEnded:Connect(NoTouch)

This is not true, but I should admit that using these events is not as easy as it might seem at first glance. I wrote a post about this for a damaging block that does x amounts of damage per second using Touched and TouchEnded: Touch event not firing correctly - #33 by Brickman808.

You can use this code to detect who is inside of a part using the events.