Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I fix this script that checks if there is an item in a model?

Asked by
Teeter11 281 Moderation Voter
10 years ago

So I am making something that requires access to a model in the players camera. BUT there is multiple items in the characters camera and they are added without a name and I CANT CHANGE THAT!! So I made a script that checks if there is a torso in the model but I get this annoying error.

Things to note : *This is in a localscript

Here is my code:

wait(1)

while wait() do
    if script.Parent.WHat.LeopardFedora.Value == true then
        camitems = game.Workspace.CurrentCamera:GetChildren()
            for i = 1,#camitems do
                if camitems[i].Torso ~= nil then -- LINE 7
                    camitems[i].LeopardFedora.Transparency = 0
                if script.Parent.WHat.LeopardFedora.Value == false then
                    camitems[i].LeopardFedora.Transparency = 1
                end
            end
        end
    end
end

ERROR : 01:35:41.857 - Torso is not a valid member of Model 01:35:41.857 - Script 'Players.Player.PlayerGui.Main.GiveWearHat', Line 7 01:35:41.858 - Stack End

Thanks if you can help!

1 answer

Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

Well I can't think of any situation that would prevent you from changing the Model's name, but your problem is

camitems[i].Torso

You're trying to check if a Torso exists, but you're already assuming it exists! camitems[i].Torso is trying to access the Torso. You don't even make it to the comparison. When you use a dot, you're making a statement. "Go to camitems[i].Torso, now." It's very direct, like an order. If it doesn't exist, however, the code can not complete your order and throws an error.

What you need is the FindFirstChild() method. It's advantage comes from the fact that it's in method form, so instead of throwing an error if the child doesn't exist, it just returns nil. Instead of, "Go get this!" you're saying something more like, "Alright, go look for this child. If he exists, bring him to me, otherwise bring me nothing."

Just remember that FindFIrstChild() will return nil at times, so it's only useful with an if statement or some other condition.

if camitems[i]:FindFirstChild("Torso") then
--Equivalent to 'if camitems[i]:FindFirstChild("Torso") ~= nil then'. Just quicker. 
0
thanks Teeter11 281 — 10y
Ad

Answer this question