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

Why does this coin collect script that I inserted in the coin not work?

Asked by 5 years ago

In my game, I inserted collectable coins, but for some reason, the script is not working and I get the message:

18:10:42.625 - Workspace.Coin.CollectScript:8: attempt to index local 'player' (a nil value)

Does somebody know what this means and how I can fix it?

This is the script inside the coin:

local db = true
script.Parent.Touched:Connect(function(hit)
    if hit.Parent:FindFirstChild("Humanoid") == nil then
        if db == true then 
            db = false
            script.Parent.Transparency = 1
            local player = game.Players:GetPlayerFromCharacter(hit.Parent)
            player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
            script.Sound.Play()
            wait(60)
            script.Parent.Transparency = 0
            db = true
        end
    end
end)

and this is the script in the workspace:

game.Players.PlayerAdded:Connect(function(plr)
    local f = Instance.new("Folder", plr)
    f.Name = "leaderstats"
    local coins = Instance.new("IntValue", f)
    coins.Name = "Coins"
    coins.Value = 0
end)

2 answers

Log in to vote
0
Answered by 5 years ago

The problem with the coins script is very simple. See line 3.

if hit.Parent:FindFirstChild("Humanoid") == nil then

That line checks if FindFirstChild returned nil. The coins could be touching another part, and because of that it fired Touched, and the part's Parent had no Humanoid inside of it. All you need to do is switch the == nil to ~= nil. However that can get messy, so simply don't have it at all:

if hit.Parent:FindFirstChild("Humanoid") then

--if not hit.Parent:FindFirstChild("Humanoid") then
-- If you want to check if it DIDN'T exist, add a 'not'

Final product:

-- I'm not checking for the humanoid anymore, as you're already checking for the player.

local db = true

script.Parent.Touched:Connect(function(hit)

    local player = game.Players:GetPlayerFromCharacter(hit.Parent)

    if db and player then -- Player may not exist! 
        db = false
        script.Parent.Transparency = 1

        player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
        script.Sound.Play()
        wait(60)
        script.Parent.Transparency = 0
        db = true
    end
end)

0
Thank you!!! Dylan011444 59 — 5y
Ad
Log in to vote
0
Answered by
piRadians 297 Moderation Voter
5 years ago
Edited 5 years ago

You set the if statement to check if the humanoid IS nil. Do this.

if hit.Parent:FindFirstChild("Humanoid") ~= nil then
-- code
end

Answer this question