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

How do I fix this? Workspace.Coin.Script:4: attempt to index nil with 'leaderstats'

Asked by 3 years ago

I am trying to make a coin but when I play I get this error: Workspace.Coin.Script:4: attempt to index nil with 'leaderstats'

When I walk over the coin it works fine but it doesn't respawn.

My code

script.Parent.Touched:Connect(function(hit)
    local player = hit.Parent:FindFirstChild("Humanoid")
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
    if plr.leaderstats.Cash.Value >= 0 then
        wait()
        script.Disabled = true
        script.Parent.Transparency = 1
        script.Parent.CanCollide = false
        plr.leaderstats.Cash.Value = plr.leaderstats.Cash.Value + 5
        wait(1)
        script.Parent.Transparency = 0
        script.Parent.CanCollide = true
        script.Disabled = false
    end
end)

0
Try to print(plr) Soban06 410 — 3y

2 answers

Log in to vote
0
Answered by 3 years ago
Edited 3 years ago

you should add something to check if the hit part is a player and you should add debounce instead of disabling the script

local db = true
script.Parent.Touched:Connect(function(hit)
    local player = hit.Parent:FindFirstChild("Humanoid")
    local plr = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then
   if plr then
    if plr.leaderstats.Cash.Value >= 0 and db == true then
    db = false
      wait()
      script.Parent.Transparency = 1
      script.Parent.CanCollide = false
      plr.leaderstats.Cash.Value = plr.leaderstats.Cash.Value + 5
        wait(1)
    db = true
        script.Parent.Transparency = 0
        script.Parent.CanCollide = true

    end
end
end
    end)

Ad
Log in to vote
0
Answered by 3 years ago

2 Issues I see with your script:

  1. You aren't checking if you hit a player's character
  2. You are disabling the script as some sort of cooldown, using a Debounce would be much better
local Players = game:GetService("Players")
local DB = false

script.Parent.Touched:Connect(function(Hit)
    local plr = Players:GetPlayerFromCharacter(Hit.Parent)
    if plr and DB == false then
        DB = true --Nobody else can trigger this while DB is true

        --Do whatever you gotta do

        wait(3)
        DB = false --waits 3 seconds, then ends the cooldown
    end
end)

Answer this question