Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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)

1 comment

0

Try to print(plr)

2 answers

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)

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)

This discussion is preserved as it was. New answers, comments, and votes are closed.