Output giving me a nil error, even if that's what I want?

Hello! I’m currently making a sound region system for my game, which checks if the player is in a part and plays a sound with the same name as the part.

I pretend to make different sounds for one region, for example, if x is equal to true it’ll play the first sound in that region, but if x is equal to false then it’ll play the second sound. I’m trying to make that work by changing the part’s name, however, it would still leave the first sound playing, so I made this code to fix that:

while true do
	for a, sound in pairs(script.Parent:GetChildren()) do
		if sound:IsA("Sound") and workspace.Map.SoundRegions[sound.Name] == nil then
			sound:Stop()
		end
	end	
end

(For context, the script is a local script located in a folder which has my sounds, while workspace.Map.SoundRegions is a folder containing the respective parts for the sounds)

Problem is, it’s giving me a nil error, telling me that [SoundPart] is not a valid member of the SoundRegions part folder… but that’s what I want, I want to check if theres no part counterpart to that sound, and if there isn’t, it’ll make the sound stop.

How can I make the code check if it’s nil without giving me an error? Any help is appreciated :wink:

You can do this:

while true do
	for a, sound in pairs(script.Parent:GetChildren()) do
		if sound:IsA("Sound") and workspace.Map.SoundRegions:FindFirstChild(sound.Name) == nil then
			sound:Stop()
		end
	end	
end

:FindFirstChild() returns nil if it doesn’t find the child, returns the child if it does.
Your code is also terrible performance-wise and functionality-wise. I suggest you use the ZonePlus module to detect whenever a player enters and exits a zone, it’s pretty great.

1 Like

My head must not be in the right place today… How could I forget about :FindFirstChild()?

I was expecting someone to say that! I’m not really familiar with stuff like that. I’ll also try ZonePlus, I still pretend to do another feature similar to what I did now.

Anyways, Thank you!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.