Hello! I was wondering if there is a way if I can have a sound start/stop when the part in my hand touches the block part? Please tell me how below!
First of all, you would have to define the two parts, as well as the sound:
local Part1 = -- tool part
local Part2 = -- other part
local sound = -- sound
I came up with three different solutions:
You could set up its .Touched event to play the sound and connect to the .TouchEnded event to stop the sound:
Part1.Touched:Connect(function(hit)
if hit == Part2 and not sound.IsPlaying then
sound:Play()
end
end)
Part1.TouchEnded:Connect(function(hit)
if hit == Part2 then
sound:Stop()
end
end)
Of course, this follows the behavior of playing the sound while touching the part and stopping the sound when the touch ends.
If you want to play the sound when touching the part, then stopping the sound when touching the part again, it would probably be useful to add a debounce and timer since last touch:
local lastHit = tick()
Part1.Touched:Connect(function(hit)
if hit == Part2 then
local now = tick()
if now - lastHit >= 0.4 then
if sound.IsPlaying then
sound:Stop()
else
sound:Play()
end
end
lastHit = now
end
end)
Note that this may not be reliable if your character is standing completely still while Part1 is inside Part2.
A different idea would be using .TouchEnded as the debounce:
local touchEnded = true
Part1.Touched:Connect(function(hit)
if hit == Part2 and touchEnded then
touchEnded = false
if sound.IsPlaying then
sound:Stop()
else
sound:Play()
end
end
end)
Part1.TouchEnded:Connect(function(hit)
if hit == Part2 then
touchEnded = true
end
end)
I will tell you that you shouldn’t be using all of this code, you can pick and choose which one best fits. I hope it was obvious…
If you have any questions, please ask.
Which part should I insert the script?
You should definitely insert the top code block:
[spoiler]Just make sure to insert the parts/sounds in place of the comments[/spoiler]
After this, you can copy one of the three code blocks below it, and see if it works.
