Trying to get the player who clicked a UI button, returns "nil"

  1. What do you want to achieve?
    I’m trying to make a function where a player’s name is inserted into a value upon clicking a button, then that value being put into a folder.

  2. What is the issue?
    When I try to get the player, the script returns “nil” instead of the player.

  3. What solutions have you tried so far?
    I’ve looked over multiple articles which have not seemed to solve my problem. One of them included putting “player” inside of the brackets that come after “function”, and then adding .Parent until you get the player. This returned an error that you cannot index “nil” with parent.

Here is my code:

local folder = script.Parent.Parent.InclPlayers
local players = game:GetService("Players")

script.Parent.MouseButton1Click:Connect(function()
	local plr = players.LocalPlayer.Name
	local AddedPlayer = Instance.new("StringValue")
	AddedPlayer.Name = plr
	AddedPlayer.Parent = script.Parent.Parent.InclPlayers
	print(plr)
end)

The script is a server script, not a local script.
I hope I explained that well enough, any help is appreciated.

what type of scrip are you using

My bad, I forgot to add. It’s a server script.

You cannot use LocalPlayer on server-side. The function MouseButton1Click gives the Player as parameter.

1 Like

You can’t access GUI elements or LocalPlayers through a server script

1 Like

I would use a RemoteEvent to do that, Player does contact thorugh Client-Side, and then the info is sent to the Server-Side through Remote Events.

try using a local script and use localplayer

1 Like

You can get responses to the MouseButton1Click event with a server script, however as others have pointed out, game.Players.LocalPlayer isn’t usable on the server.

You should also be using LocalScripts for catching click events anyways. Using a LocalScript and a RemoteEvent for creating the object would be a lot easier, because you can use game.Players.LocalPlayer on the client. If you insist on doing this on the server only without RemoteEvents, you can have a long chain of script.Parent until you reach the Player object.

If you would like more information on RemoteEvents, you can read about them here.

1 Like

You can’t use Gui objects and .LocalPlayer in a server script.