The for loop is executed only once

I am working on a script to control SpotLight, which is a children of the “Light” part in the “Body” model.
I want to use a For loop so that if there are multiple Lights in the Body, they will all light up.
However, only one of the SpotLights will work.
There are many similar questions on the forum, but using GetDescendants did not change the result.

for i ,v in pairs(seat.Parent.Body:GetChildren()) do
	if v.Name == "Light" then
	v.SpotLight.Enabled = not v.SpotLight.Enabled
	end
end

can you please provide more information, maybe screenshot the children of the ‘Body’ model ???

スクリーンショット 2022-08-01 20.39.21
It looks like this.

Where is the script located? Can you screenshot the path of the current script?

Since this script is located within the driving GUI (LocalScript), it is cloned to the player the moment the player sits in the VehicleSeat.
Currently there are two Lights in the Body, one of which is working correctly.
Thus, I do not believe it is a path specification error.

Try print the children of the “Body” object

Two Lights will be printed.
It is printed twice at the same time, not (x2).

it might be because it maybe gets destroyed, try checking on it via explorer page and and use print

maybe you’ve spelt the name ‘Light’ wrong so double check that too (you could of added a space at the end of the ‘Light’ so the script wouldn’t register it)

for i, v in pairs(seat.Parent.Body:GetChildren()) do
	print(v.Name, v.ClassName, i)
	if v.Name == 'Light' then
		print('found light', i)
		v.SpotLight.Enabled = not v.SpotLight.Enabled
	end
end
for _, Light in ipairs(seat.Parent:GetDescendants()) do
   if not Light:IsA("SpotLight") then continue end
   Light.Enabled = not Light.Enabled
end

You could try this

1 Like

I changed it to one letter (e.g., L) because there could be a typo in Light, but the result did not change.

A few modifications to this and it works!
Thank you all for the great suggestions. @cxsmie @Minhseu123

1 Like

スクリーンショット 2022-08-01 21.05.40
Finally, the name and other details were changed to this.
Works perfectly.

1 Like