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

Why is my function returning error ":attempt to index with nil"?

Asked by 4 years ago

Ok, so here's my script. Its in a gui in starterGui:

local button = script.Parent
button.MouseButton1Click:connect(function()
    local player = game.Players.LocalPlayer
    local ShirtValue = 56082616
    local PantsValue = 56079978
    local shirt = player:FindFirstChild("Shirt")
    local pants = player:FindFirstChild("Pants")
    pants.PantsTemplate = "http://www.roblox.com/asset/?id="..PantsValue
    shirt.ShirtTemplate = "http://www.roblox.com/asset/?id="..ShirtValue
end)

Every time I click on the button, I get the error message :attempt to index nil with 'PantsTemplate'. I've tried different ways of writing this line of code:

pants.PantsTemplate = "http://www.roblox.com/asset/?id=56079978"

and

pants.PantsTemplate = "56079978"

and

pants.PantsTemplate = 56079978

and

pants.PantsTemplate = "rbxassetid://56079978"

All of these versions return the same error. Any ideas why? Perhaps you cannot change PantsTemplate and ShirtTemplate like that?

1 answer

Log in to vote
0
Answered by
Ziffixture 6913 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

This is because you're trying to find something that isn't a derivative of Player; logically, the Pants & Shirts Objects would be apart of the avatar rig.

Your program didn't catch this because you used :FindFirstChild(), which is used for the potential scenario of an Instance non-existence, and providing a nil return instead of a raised exception (error). It's best to use this method in conjunction with a conditional, to ensure we're actually using an existing asset:

local Player = game:GetService("Players").LocalPlayer

local ShirtAssetId = 56082616
local PantsAssetId = 56079978

local Button = script.Parent

Button.MouseButton1Click:Connect(function()
    local Character = Player.Character or Player.CharacterAdded:Wait()
    local Shirt = Character:FindFirstChild("Shirt")
    local Pants = Character:FindFirstChild("Pants")
    if (Shirt and Pants) then
        Shirt.ShirtTemplate = "rbxassetid://"..ShirtAssetId
        Pants.PantsTemplate = "rbxassetid://"..PantsAssetId
    end
end)

If this helps, don't forget to accept this answer!

0
thanks. Although u would have to change Shirt.PantsTemplate to Pants.PantsTemplate or it wont work. sergeant_ranger 184 — 4y
Ad

Answer this question