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

Find Local Player In NON-LocalScripts?

I am trying to make a game where you claim a plot of land and farm on it and the claiming part will not work for me. It gives me an error saying that locplayer is not a part of Players and this is my code...

local plotowner
local plot = script.Parent
local vacant = true
local Players = game:GetService("Players")

game.Players.PlayerAdded:Connect(function(player)
  	local locplayer = player.Name
end) 

local function onPartTouched(otherPart)
	if vacant == true then
		-- Get the other part's parent
		local partParent = otherPart.Parent
		-- Look for a humanoid in the parent
		local humanoid = partParent:FindFirstChildWhichIsA("Humanoid")
			if humanoid then
				if Players.locplayer["HasPlot?"] == true then
				print("ALREADY HAVE A PLOT!")
			else
				Players.locplayer["HasPlot?"] = true
				print("PLOT HAS BEEN CLAIMED!")
				vacant = false
			end
		end
	end			
end

	
 
plot.Touched:Connect(onPartTouched)

1 comment

0

otherpart.Parent is the players character if a player was the thing that touched it. So you would do GetPlayerFromCharacter. If you look it up it should show you how to use it

2 answers

You can't find the LocalPlayer on the server, as there is no Local Player (The server doesn't run on any clients computer, so there is no local player in control of it.)

However, there are several ways to have access to a player object. Some event listeners pass the player as an argument to the function, as you are doing with the PlayerAdded function. However, you are attempting to use that player, which you have given the name locplayer, outside the scope of that function which is why it isn't working.

The Touched event doesn't pass you the player object, but it does pass you the part that was touched. A handy function you can use to find the player from this is GetPlayerFromCharacter(). So in your script, after checking if the humanoid exists:

local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if player["HasPlot?"] == true then
	print("ALREADY HAS PLOT!")
else
	player["HasPlot?"] = true
	print("plot has been claimed!")
	vacant = false
end

RemoteEvents, probably.

--LocalScript
local plr = game.Players.LocalPlayer
local event = workspace.RemoteEvent --Or any other location

event:FireServer(plr.Name)

-Script
local event = workspace.RemoteEvent

event.OnServerEvent:Connect(function()
	--Do whatever here
end)

FireServer() does get the player no matter what you specify, though.

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