Attempt to index nil with 'cash'

Hiya developers!

I seem to be getting this error from my server script .

  18:06:01.050  Workspace.Vault.Script:19: attempt to index nil with 'Cash'  -  Server - Script:19

Here is my code.

local players = game:GetService("Players")
local canRob = true

script.Parent.Touched:Connect(function(Hit)
	if Hit and Hit.Parent:FindFirstChild("Humanoid") then
		local humanoid = Hit.Parent:FindFirstChild("Humanoid")
		local player = players:GetPlayerFromCharacter(humanoid.Parent)
		local Playername = player.Name
		
		
		print(Playername)
		
		
		
		
		while true do
			canRob = true
			task.wait(3, 8)
			Playername.leaderstats.Cash.Value += math.random(1, 12)	
			repeat until canRob == false
			
		end
		task.wait(15)
		canRob = false
		print("Stopped robbing")

		
		


	end
end)

Any help is appreciated!

1 Like

Change:

To:


player.leaderstats.Cash.Value += math.random(1, 12)
3 Likes

I’m sure ‘Playername’ is a string and not an instance so should not have leaderstats attached to it.

1 Like

I optimize the code to fix a few problems that I think you had. And of course your original error should be fixed:

local players = game:GetService("Players")
local canRob = true

script.Parent.Touched:Connect(function(hit)
	local player = game.Players:GetPlayerFromCharacter(hit.Parent)
	if player then
		canRob = true
		task.spawn(function()
			while canRob do
				task.wait(math.random(3,8))
				if not canRob then return end
				player.leaderstats.Cash.Value += math.random(1, 12)
			end
		end)

		task.wait(15)
		canRob = false
	end
end)
1 Like

Thanks for this. I’ll be sure to change it to this :slight_smile:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.