How can I make the audio play when the player isn't near any light sources and stop if the player is near a light sources?

The error must have occured when there were no lights on workspace. I solved the error and I also made it so it detects if the light is enabled or not.

local RunService = game:GetService("RunService")
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local hum = char:WaitForChild("Humanoid")
local sound = workspace.Heartbeat
local maxDist = 100


local lights = {}

RunService.Heartbeat:Connect(function()

	for i,v in pairs(workspace:GetDescendants()) do -- scans through workspace 
		local light = v:FindFirstChildWhichIsA("Light")
		if light ~= nil and v:IsA("BasePart") then
			if light.Enabled == true then
				local dist = plr:DistanceFromCharacter(v.Position)
				table.insert(lights,dist)
		    end
		end
	end
	
	local hasLight = lights[1]
	if hasLight == nil then return end
	
	local totalLights = 0
	for i,v in pairs(lights) do
		totalLights += 1
	end

	if totalLights > 1 then
		table.sort(lights, function(a,b)
			return a<b
		end)
	end
	
	local dist = lights[1]

	if dist < maxDist then
		if sound.IsPlaying == true then
			-- detect if it's playing
			sound:Stop()
		end

	elseif dist > maxDist then
		if sound.IsPlaying == false then
			-- detects if it's not playing, also fixes the bug 
			-- that doesn't play the sound as expected
			sound:Play()
		end
	end

	lights = {}

	
end)

It worked! but when I turn the lighter on and off the sound didn’t replay

Ah, I know what you’re trying to say. I forgot to make it so it plays when there is no light.

Anyway find this code

local hasLight = lights[1]
if hasLight == nil then return end

The replace that code to this

local hasLight = lights[1]
if hasLight == nil then 
	if sound.IsPlaying == false then
		sound:Play()
	end
		
	return 
end

Also, don’t forget to mark this as a solution if it has been fixed for you.

1 Like

It work perfectly fine now thank you so much for your time!

1 Like