Hello!
I just want do when play is in region then music starts play that works BUT
When player left that region I want it stop but that’s not happening
Here script
local Region = Region3.new(workspace.k.Position - (workspace.k.Size/2),workspace.k.Position + (workspace.k.Size/2))
local found = false
while wait(0.2) do
local parts = game.Workspace:FindPartsInRegion3WithWhiteList(Region,game.Players.LocalPlayer.Character:GetDescendants())
for _,s in pairs(parts) do
if s:FindFirstAncestor(game.Players.LocalPlayer.Name) then
print("found")
found = true
if script.Sound.IsPlaying == false then
script.Sound:Play()
end
break
elseif not s:FindFirstAncestor(game.Players.LocalPlayer.Name) then
if script.Sound.IsPlaying == true then
script.Sound:Stop()
end
found = false
print("NOOO")
end
end
end
I think there’s a better way to organize your script, by limiting how many parts to find in the whitelist:
local Region = Region3.new(workspace.k.Position - (workspace.k.Size/2),workspace.k.Position + (workspace.k.Size/2))
while wait(0.2) do
local parts = workspace:FindPartsInRegion3WithWhiteList(
Region, -- region3
{game.Players.LocalPlayer.Character}, -- whitelist
1 -- maxParts
)
if next(parts) ~= nil then -- checks to see if any elements exist in the table
print("found")
else
print("NOOO")
end
end
This should help you single out when the sound should start and stop playing better. No need for a for loop.
Better organized code
local Workspace = game:GetService("Workspace")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local kPart = Workspace.k
local Region = Region3.new(
kPart.Position - kPart.Size/2,
kPart.Position + kPart.Size/2
)
while true do
local parts = Workspace:FindPartsInRegion3WithWhiteList(
Region,
{player.Character},
1
)
if next(parts) then
print("found")
else
print("NOOO")
end
wait(0.2)
end