Problem with GetPlayerFromCharacter?

So I’m making an object that upon being touched, would give the player an item and deduct the player’s cash. My code is as follows:

local RedCircle = script.Parent
local price = script.Parent.Parent.Price
local TeamOn = script.Parent.Parent.Team
local playeronteam = TeamOn.Name.."TeamPlayer"

local Players = game:GetService("Players")

--local PlayerWhoOwnsCastle = game.Workspace[playeronteam].Value
RedCircle.Touched:Connect(function(hit)
	if hit.Parent:FindFirstChild("Humanoid") then
		local player = Players:GetPlayerFromCharacter(hit.Parent.Humanoid)
	--	print(player.Name)
		player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 20
	end
end)

I get the error:

  Workspace.Buy Barracks - [$10].Head.Script:13: attempt to index nil with 'leaderstats'

Why is this? My hierarchy is as follows:
Screen Shot 2021-05-24 at 1.39.15 PM

1 Like

Add an if statement to check whether the player exists or not.

if player then
    player.leaderstats.Cash.Value = player.leaderstats.Cash.Value - 20
end

You’re also passing the humanoid as the GetPlayerFromCharacter argument.

you dont reference the humanoid. i think you use the character itself

This is correct, you need to change local player = Players:GetPlayerFromCharacter(hit.Parent.Humanoid) to local player = Players:GetPlayerFromCharacter(hit.Parent).

2 Likes