Ad
Still have questions? Join our Discord server and get real time help.
Log in to vote
0

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

Asked by 2 years ago
Edited 2 years ago

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)
0
the player argument in the function is the player so the line 2 is usless abnotaddable 895 — 2y
0
How should it know that you want the player who clicked it to be the local player? hiimgoodpack 2009 — 2y
0
That is one of my problems that I do not know how to deal with. BunnyFilms1 218 — 2y

3 answers

Log in to vote
1
Answered by 2 years ago
Edited 2 years ago

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.

0
THANKS U FIXED MY PROBLEM Xanfar38 -3 — 1y
Ad
Log in to vote
0
Answered by
H4X0MSYT 536 Moderation Voter
2 years ago

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.

0
So how would I make an "arg" with onClicked with a click detector? BunnyFilms1 218 — 2y
0
You can't script can you? H4X0MSYT 536 — 2y
Log in to vote
0
Answered by
A_thruZ 29
1 year ago

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.

Answer this question