Error when checking cash val of player

I’m getting an error saying Players.TSF_Lacker.PlayerGui.ScreenGui.Frame.NormalCrate.Script:4: attempt to index nil with ‘leaderstats’


local DataStoreService = game:GetService("DataStoreService")

local myDataStore = DataStoreService:GetDataStore("myDataStore")

game.Players.PlayerAdded:Connect(function(player)
	
	local i = Instance.new("Folder")
	i.Name = "leaderstats"
	i.Parent = player
	
	local v = Instance.new("IntValue")
	v.Name = "Cash"
	v.Parent = i
	
	
	local data1
	local success, errormessage = pcall(function()
		data1 = myDataStore:GetAsync(player.UserId.."-Cash")
	end)
	
	if success then
		v.Value	= data1
		print("Successfuly saved data")
	else
		print("There was an error whilst getting your data")
		warn(errormessage)
	end
end)

game.Players.PlayerRemoving:Connect(function(player)
	
	local success, errormessage = pcall(function()
	myDataStore:SetAsync(player.UserId.."-Cash",player.leaderstats.Followers.Value)
	end)
	
	if success then
		print("Player data successfully saved!")
	else
		print("There was an error when saving data")
		warn(errormessage)
	end
end)
--Datastore script

local player = game.Players.LocalPlayer

script.Parent.MouseButton1Click:Connect(function()
	if player.leaderstats.Cash >= 0 then
		script.Parent.Visible = false
		script.Parent.Parent.NormalCratePrice.Visible = false
		script.Parent.Parent.SkinGiver.Visible = true
		script.Parent.Parent.SkinName.Visible = true
	end
end)
end)

--Text Button Script

I’m getting an error saying Players.TSF_Lacker.PlayerGui.ScreenGui.Frame.NormalCrate.Script:4: attempt to index nil with ‘leaderstats’

The code doesn’t match with line 4. Also why is this in PlayerGui? This is not where server scripts go. This should be in ServerScriptService.

1 Like

it is under a text button in starter gui

Well it should not be there since 1. that should not work and 2. your script is not manipulating any GUI and even if it were it should be a local script. Move it to ServerScriptService.