Only 2 Areas Play Sound

Hi! I’m trying to make a thing where when you’re in a specific area, you can hear different sounds. I have three areas where different music plays. But only 2 areas make sound.
here’s the script:

local AreaSounds = Instance.new("Sound", script)
AreaSounds.Looped = true
local plr = script.Parent
local Presser = plr:WaitForChild("HumanoidRootPart")
local DifferentAreas = workspace:WaitForChild("Music")
local CurrentArea = nil

game:GetService("RunService").Heartbeat:Connect(function()
	local raycast = Ray.new(Presser.Position, Presser.CFrame.UpVector * -1000)
	local part = workspace:FindPartOnRayWithWhitelist(raycast, {DifferentAreas})
	if part and part.Parent == DifferentAreas then
		if part ~= CurrentArea then
			CurrentArea = part
			AreaSounds.SoundId = CurrentArea.Sound.SoundId
			AreaSounds:Play()
		end 
	else
		CurrentArea = nil
		AreaSounds:Stop()
	end
end)

I tried decreasing the -1000 but that didn’t work. So I don’t know what to do. Can someone help?

Hello there. It looks like the issue is with how the ray is detecting the areas. I’ve made a few improvements to your script that should fix the problem. Here’s the explanation:

  1. Raycasting Method: The way you’re casting the ray was a bit outdated. I changed it to use workspace:Raycast(), which is more accurate and works better for detecting parts.
  2. Filtering Areas: I also made sure the ray only looks for parts in the Music folder, so it doesn’t accidentally detect other objects in the game.
  3. Area Setup: Make sure all the areas in your Music folder are Parts, not Models, and each part has a Sound object inside it. If one of the areas is set up differently, the ray might not detect it.

Here’s the script:

local AreaSounds = Instance.new("Sound", script)
AreaSounds.Looped = true
local plr = script.Parent
local Presser = plr:WaitForChild("HumanoidRootPart")
local DifferentAreas = workspace:WaitForChild("Music")
local CurrentArea = nil

local rayParams = RaycastParams.new()
rayParams.FilterType = Enum.RaycastFilterType.Whitelist
rayParams.FilterDescendantsInstances = {DifferentAreas}

game:GetService("RunService").Heartbeat:Connect(function()
	local origin = Presser.Position
	local direction = Vector3.new(0, -1000, 0)
	local result = workspace:Raycast(origin, direction, rayParams)

	if result and result.Instance and result.Instance.Parent == DifferentAreas then
		if result.Instance ~= CurrentArea then
			CurrentArea = result.Instance
			local soundObj = CurrentArea:FindFirstChild("Sound")
			if soundObj then
				AreaSounds.SoundId = soundObj.SoundId
				AreaSounds:Play()
			end
		end
	else
		if CurrentArea then
			CurrentArea = nil
			AreaSounds:Stop()
		end
	end
end)

To check:

  • Make sure all three areas in the Music folder are Parts (not Models) and have a Sound object inside.
  • Ensure collision is enabled on the parts so the ray can detect them properly.

This should work.

2 Likes