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

Help With If Statements?

Asked by
Scootakip 299 Moderation Voter
8 years ago
while true do
    wait(.5)
    local player = game.Players.LocalPlayer.Character
    if player then
        local oldpants = player.Pants
        local oldshirt = player.Shirt
        if oldpants then
            player.Pants:Destroy()
        end
        if oldshirt then
            player.Shirt:Destroy()
        end
    end
end

I need this script to destroy a shirt and pants if a player is wearing them. However, if the player isn't wearing a shirt or pants already, the script breaks. How do I fix it to not break like that?

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

If an object doesn't exist, e.g., player.Pants, you don't get nil. You get an error.

If you aren't sure that an object exists, you can use parent:FindFirstChild(childname) to search for it. It will instead return nil if it doesn't exist.

As an aside: don't do something like player.Pants:Destroy() since you have the variable oldpants that already has it. Use variables if you have defined them.

local oldpants = player:FindFirstChild("Pants")
if oldpants then
    oldpants:Destroy()
end
Ad

Answer this question