Could I simplify this code?

Hello!
I am currently working on a FNAF fangame.
When you change the cameras. A sound is playing.

But I think my code isn’t the best. Here it is:

local Sound = script.Parent.Parent.ChangeCamSound
local Map = script.Parent
Local SecondFloor = script.Parent.SecondsFloor -- Yes there is a second floor
function Changing()
Sound:Play()
end


Map.Cam01.MouseClick:Connect(Changing)

-- This goes on until Cam08.

SecondFloor.Cam09.MouseClick:Connect(Changing)
SecondFloor.Cam10.MouseClick:Connect(Changing)

-- I might add a debounce too.

So is there anyways to improve my code? To make it more simple. I think I should separate the floors to not mess up the script since they have different Parents.

1 Like

If you want to make it look better then I guess you could maybe do this

local Map = script.Parent
local Sound = Map.Parent.ChangeCamSound
local SecondFloor = Map.SecondsFloor -- Yes there is a second floor

local function Changing()
     Sound:Play()
end

Map.Cam01.MouseClick:Connect(Changing)
-- This goes on until Cam08.
SecondFloor.Cam09.MouseClick:Connect(Changing)
SecondFloor.Cam10.MouseClick:Connect(Changing)

-- I might add a debounce too.
1 Like

You could use a loop to go through what contains the word Cam in the name of a descendant of the Map and connect the event from there instead of direct references

for _,detector in pairs(Map:GetDescendants()) do
	if detector.ClassName ~= "ClickDetector" or not string.match(detector.Name, "Cam") then
		continue
	end
	detector.MouseClick:Connect(Changing)
end

Checks if what is currently iterated over is a ClickDetector and it has the word Cam in its name, if either is not correct, it continues to the next thing in the Map, otherwise, it connects the MouseClick event.

If you have tons of stuff in your map, I recommend you just put the cameras in their own folder and loop through that folder instead and connect the events

5 Likes

I do not know if this is important. But my ChangeCamera buttons are UIs.

2 Likes

MouseClick seems to indicate that they are ClickDetectors, but generally the same principle applies, you just need to change some of the code to make it work with your UIs

2 Likes

So, what do I use for the ClassName. Do I just say "TextButton"?

1 Like

Yup, The if statement basically just checks if the class name is not ClickDetector or Cam is not in the name, if you change ClickDetector to the class you want to check, it’ll still work, and you’d have to change the MouseClick event to the name of the event you want to use

2 Likes

Thank you! Now it seems more clear to me!

2 Likes

Hello! I recently made another post, it’s a bit like this one.

Review/feedback on CameraSystem, can I improve? - Help and Feedback / Code Review - DevForum | Roblox

1 Like