Getting Player From Tool

So, I have a tool that when activated gives the player 1 food. But, I am using a server script to script the tool. How would I get the player obj from a server script?
Here is the script so far:

local db = false

local plr

script.Parent.Activated:Connect(function()
	if db ~= false then return end
	
	local stats = game:GetService("ReplicatedStorage"):FindFirstChild("PlrStats"):FindFirstChild("PlrStats"):FindFirstChild(plr.Name):FindFirstChild("Food")
	
	if stats then
		stats.Value = stats.Value + 1
	end
	
end)
10 Likes

Since when you equip a tool, it is placed inside of the character, you can just use :GetPlayerFromCharacter to get it.

local Player = game:GetService("Players"):GetPlayerFromCharacter(tool.Parent)
7 Likes

GetPlayerFromCharacter

--assuming the script is directly under the tool
local player = script:FindFirstAncestorWhichIsA"Player" or game:GetService"Players":GetPlayerFromCharacter(script.Parent.Parent)
19 Likes

With your solution I got:
Players.GamingBroCoolkid328.Backpack.Tool.EatScript:8: attempt to index upvalue 'plr' (a nil value)
I think it’s because it’s running when the tool is not equipped? :thinking:

1 Like

Put the variable inside of the activated event.

Ok, I had to do that with the other one too. I already got everything working, but thank you! :smiley:

1 Like

uh it says that GetPlayerFromCharacter is unsafe and also it also says that
“For thread safety, this property is not safe to read in an unsynchronized thread.”
and i don’t know what that means, but try this, it works?
local Players = game:GetService("Players)
local Player = script:FindFirstAncestorWhichIsA(“Player”) or Players:FindFirstChild(script:FindFirstAncestorWhichIsA(“Model”).Name)

1 Like