How can I simplify this? (Listen Event)

The purpose of this script is to listen out for any changes in a value. Instead of copying and pasting it again and again, what is a method that I could use to simplify this? It needs to be easily accessed throughout the code.

Here is the code:

local Phobia1 = Phobias:WaitForChild("Phobia1")
local Phobia2 = Phobias:WaitForChild("Phobia2")
local Phobia3 = Phobias:WaitForChild("Phobia3")
local Phobia4 = Phobias:WaitForChild("Phobia4")

--{CHECK FUNCTION}--
local function CheckComplete(PhobiaBool)
	local PhobiaText = ListFrame:FindFirstChild(tostring(PhobiaBool))
	if PhobiaBool.Value then
		PhobiaText.BackgroundColor3 = Color3.fromRGB(156,255,134)
	else
		PhobiaText.BackgroundColor3 = Color3.fromRGB(0,0,0)
	end
end

--{FIRST UPDATE}--
CheckComplete(Phobia1)
CheckComplete(Phobia2)
CheckComplete(Phobia3)
CheckComplete(Phobia4)

--{LISTEN FOR CHANGE}--
Phobia1.Changed:Connect(function()
	CheckComplete(Phobia1)
end)

Phobia2.Changed:Connect(function()
	CheckComplete(Phobia2)
end)

Phobia3.Changed:Connect(function()
	CheckComplete(Phobia3)
end)

Phobia4.Changed:Connect(function()
	CheckComplete(Phobia4)
end)

Another section:

local P1 = ListFrame.Phobia1
local P2 = ListFrame.Phobia2
local P3 = ListFrame.Phobia3
local P4 = ListFrame.Phobia4
local P5 = ListFrame.Phobia5
local P6 = ListFrame.Phobia6
local P7 = ListFrame.Phobia7
local P8 = ListFrame.Phobia8
local P9 = ListFrame.Phobia9
local P10 = ListFrame.Phobia10

Go through all the phobias using a generic for loop.

for _, phobia in ipairs(Phobias:GetChildren()) do
    phobia.Changed:Connect(function()
        CheckComplete(phobia)
    end)
end)

And do similar for that last script.

2 Likes

I understand your method for the first section. For the second section, will I be able to use it as a variable for future lines?

You might use dictionaries here :

local Phobias = {}
 -- and then assign the values inside the dictionary
for _,phobia in pairs(ListFrame:GetChildren()) do
    Phobias[phobia.Name] = phobia
end

>>print(Phobias.Phobia1.Name) 
>> Phobia1
1 Like

You’ll have to do it in the for loop.

You could also have a few variables set to nil if you really need them.

1 Like