Where did I go wrong with this loop?

So, I am making a loop that (once a button is clicked) finds all of a model’s children and sets their trancparency to 1. However, this part of Lua is new to me, and I don’t understand it that well. Whenever I click the button, I just get the error “attempt to call a nil value.” Sorry if this is a bit vague, but can someone tell me what I need to fix? Thanks!

The code:

local model = game.Workspace:FindFirstChild(“TestCube”):GetChildren()

script.Parent.MouseClick:Connect()

for i, v in pairs(model) do

v.Trancparency = 1

end

So with the current script you provided, line one is getting all the children of the Cube at the point the script is running, which is basically as soon as it possibly can. This means any child objects added to the cube after that line has ran, will not be detected.

Then you have it so when the mouse clicks, it goes through those objects and assumes everything in there has a property called Trancparency which is not the case as that is a mispelling of Transparency, and only a few objects have that property.

What you need to do is get the children when the mouse is clicked instead of before, and make sure the the objects it finds are objects with Transparency properties. If you know what to look for, such as Parts, or Frames, you can do this by checking: if v:IsA(“BasePart”) then change set the transparency.

Here is a visual example:

script.Parent.MouseClick:Connect(function()
	local model = workspace:FindFirstChild("TestCube")
	if model then
		for k,v in pairs(model:GetChildren()) do
			if v:IsA("BasePart") then
				v.Transparency = 1
			end
		end
	end
end)

Hope this helps! :slight_smile:

Thanks, that really helped. I didn’t even notice I spelled Transparency wrong, lol, it’s been a long day.

1 Like
local model = workspace:FindFirstChild("TestCube")

script.Parent.MouseClick:Connect(function()
	for _, child in pairs(model:GetChildren()) do
		if child:IsA("BasePart") then
			child.Transparency = 1
		end
	end
end)

I’d do it this way, that way you’re not checking “model” since it exists from the server starting also there’s no need to keep redeclaring a variable for “model”, once at the top of the script before the function is connected to the “MouseClick” event is fine.

Yes, your way is better in case TestCube was reparented to something else. However if it was destroyed, then it would start erroring because the variable containing the model can no longer be used. That’s why I opted to have it find the model each time before attempting to get its children. :slight_smile: