while true and wait() do for o,p in pairs(game.Players:getChildren()) do if (p.Character:findFirstChild("Torso").Position-script.Parent.Position).magnitude<10 then script.Parent.Sound:Play() else script.Parent.Sound:Stop() end end end
What is the most efficient way on making it so it plays once, and if you're over the magnitude of "10" then it stops? Also, how would I make it so the sound only plays to the certain character? Cloning the Sound into the Character, then playing it?
Help would be appreciated.
I recommend you use Coroutines and Debounce. Coroutines so you can accurately check if the player is near the part, and debounce so only play the sound once. Alternatively to coroutines, you can use the PlayerAdded() and CharacterAdded() events, so that it runs on a separate thread and works for every player without having to rescan them. Also, do you want the sound to be played once and once only, or do you want it to play whenever the player steps near the part, so that it will remain repeatable? In the finished script I made, it's repeatable and cuts whenever the player steps out of range.
Finished Script:
--Assuming the sound is named Sound and is located in StarterGui local debounce = {} game.Players.PlayerAdded:connect(function(player) player.CharacterAdded:connect(function(character) while true do if not (player or character) then break end if (character:FindFirstChild("Torso").Position-script.Parent.Position).magnitude<=10 then if not debounce[player.Name] then debounce[player.Name] = true player.PlayerGui.Sound:Play() end else debounce[player.Name] = nil player.PlayerGui.Sound:Stop() end wait() end end) end)