Right now I have it where if a player touches a part in a specific folder then the function “checkIsInRegion” will be called. Although if the player constantly interacts with that part the function will keep being called over and over again whenever the player is interacting with the part. I only want it where the function will play once and not again until a different part in the specific folder is touched.
In this case I have a musicRegion local script which clones and plays a song whenever a player enters a region by calling the “checkIsInRegion” function:
local plr = game.Players.LocalPlayer
local char = nil
local rs = game:GetService("RunService")
local regions = {}
local regiontouched = false
for i, v in pairs(workspace.MusicRegions:GetChildren()) do
local soundClass = v:FindFirstChildOfClass("Sound")
if soundClass then
local tab = {
["CFrame"] = v.CFrame,
["Sound"] = soundClass,
["Active"] = false,
["Size"] = v.Size,
["Volume"] = soundClass.Volume,
["SoundClone"] = nil,
}
soundClass.Looped = true
tab.Sound.Volume = tab.Volume
table.insert(regions, tab)
end
end
local activeSoundClone = nil
function stopAndDestroySound(sound)
if sound then
sound:Stop()
sound:Destroy()
end
end
function cloneAndPlaySound(sound)
local newSoundClone = sound:Clone()
newSoundClone:Play()
newSoundClone.Parent = plr
if plr.PlayerGui:FindFirstChild("Menu").SettingsMenu.Pages.AudioPage.Frame["Mute/Unmute"].Muted.Value then
newSoundClone:Pause()
elseif not plr.PlayerGui:FindFirstChild("Menu").SettingsMenu.Pages.AudioPage.Frame["Mute/Unmute"].Muted.Value then
newSoundClone:Play()
end
return newSoundClone
end
function checkIsInRegion()
local inRegion = false
local currentActiveRegion = nil
regiontouched = true
for i, v in pairs(regions) do
local ovlapparams = OverlapParams.new()
ovlapparams.FilterType = Enum.RaycastFilterType.Whitelist
ovlapparams.FilterDescendantsInstances = {char}
local found = #workspace:GetPartBoundsInBox(v.CFrame, v.Size, ovlapparams) > 0
if found then
inRegion = true
currentActiveRegion = v
v.Sound:Pause()
if not v.Active then
v.Active = true
if activeSoundClone then
stopAndDestroySound(activeSoundClone)
end
activeSoundClone = cloneAndPlaySound(v.Sound)
end
else
v.Active = false
end
end
if not inRegion then
stopAndDestroySound(activeSoundClone)
activeSoundClone = nil
end
end
plr.CharacterAdded:Connect(function()
char = plr.Character
local rootPart = char:WaitForChild("HumanoidRootPart")
rootPart.Touched:Connect(function(otherPart)
if otherPart:IsDescendantOf(workspace.MusicRegions) then
-- only want this function to be called once for each region
checkIsInRegion()
else
return
end
end)
end)
Any help is appreciated, thanks.