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

How Do I Get The Local Player From A Server Script?

So I have had an issue with values not saving to a leaderboard because it was a local script so here I have a server script I made but I get the following error:

Script:3: attempt to index local 'user' (a nil value)

So the problem is, how do I get the player who clicked the text button in a server script?

local function onClicked(player)
	local user = game.Players:GetPlayerFromCharacter(player)
		local stats = user:findFirstChild("leaderstats")
		if stats ~= nil then
			local cash = stats:findFirstChild("Money")
			cash.Value  = cash.Value + 500
	else
		print("Error1")
	end
end

script.Parent.MouseButton1Click:connect(onClicked)

3 comments

0

the player argument in the function is the player so the line 2 is usless

0

How should it know that you want the player who clicked it to be the local player?

0

That is one of my problems that I do not know how to deal with.

3 answers

✓ Accepted answer

This script is supposed to be a LocalScript (read this guide; servers cannot handle user input directly when playing online). You have up to 2 other problems:

  1. The client (ie any LocalScript) isn't supposed to change things like the leaderstats. Instead, the client is supposed to use a RemoteEvent/RemoteFunction (see tutorial) to communicate to the server what it wants changed. (This is for FilteringEnabled places [aka non-Experimental Mode].)
  2. MouseButton1Click does not give any arguments. Instead, when you're in a LocalScript, simply use game.Players.LocalPlayer.

ie, change line 2 to be local user = game.Players.LocalPlayer, make it a LocalScript, and turn on experimental mode (aka turn off FilteringEnabled) if needed and it should work.

1 comment

0

THANKS U FIXED MY PROBLEM

Only client side items can grab localplayer. Use an argument, like ontouched for example. Its arg is the part that touched it. Same applies to click-detectors.

2 comments

0

So how would I make an "arg" with onClicked with a click detector?

0

You can't script can you?

To access the local player from a script, you could use something like this:

local players = game.Players
wait(1)
local camera = workspace.Camera
local player = nil
for i, v in pairs(players:GetPlayers()) do
	if v.Name ~= camera.CameraSubject.Parent.Name then
		player = v
	end
end

This will only work if the camera subject is the character, though.

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