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 6 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:

01local db = true
02script.Parent.Touched:Connect(function(hit)
03    if hit.Parent:FindFirstChild("Humanoid") == nil then
04        if db == true then
05            db = false
06            script.Parent.Transparency = 1
07            local player = game.Players:GetPlayerFromCharacter(hit.Parent)
08            player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
09            script.Sound.Play()
10            wait(60)
11            script.Parent.Transparency = 0
12            db = true
13        end
14    end
15end)

and this is the script in the workspace:

1game.Players.PlayerAdded:Connect(function(plr)
2    local f = Instance.new("Folder", plr)
3    f.Name = "leaderstats"
4    local coins = Instance.new("IntValue", f)
5    coins.Name = "Coins"
6    coins.Value = 0
7end)

2 answers

Log in to vote
0
Answered by 6 years ago

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

1if 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:

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

Final product:

01-- I'm not checking for the humanoid anymore, as you're already checking for the player.
02 
03local db = true
04 
05script.Parent.Touched:Connect(function(hit)
06 
07    local player = game.Players:GetPlayerFromCharacter(hit.Parent)
08 
09    if db and player then -- Player may not exist!
10        db = false
11        script.Parent.Transparency = 1
12 
13        player.leaderstats.Coins.Value = player.leaderstats.Coins.Value + 1
14        script.Sound.Play()
15        wait(60)
16        script.Parent.Transparency = 0
17        db = true
18    end
19end)
0
Thank you!!! Dylan011444 59 — 6y
Ad
Log in to vote
0
Answered by
piRadians 297 Moderation Voter
6 years ago
Edited 6 years ago

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

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

Answer this question