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:
01 | local db = true |
02 | script.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 |
15 | end ) |
and this is the script in the workspace:
1 | game.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 |
7 | end ) |
1 | if hit.Parent:FindFirstChild( "Humanoid" ) = = nil then |
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:1 | if 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' |
01 | -- I'm not checking for the humanoid anymore, as you're already checking for the player. |
02 |
03 | local db = true |
04 |
05 | script.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 |
19 | end ) |
You set the if statement to check if the humanoid IS nil. Do this.
1 | if hit.Parent:FindFirstChild( "Humanoid" ) ~ = nil then |
2 | -- code |
3 | end |