How to get the username of a player in a server script

I am making a car spawner and am trying to get the username of the player who clicked it

local player

game.Players.PlayerAdded:Connect(function(Player)
	player = Player
end)
script.Parent.MouseButton1Click:connect(function(GetCar, player)
		local Mod = game.ServerStorage.lambo1     
	    local clone = Mod:clone()
	    clone.Parent = workspace
	    clone.name = player.name
		clone:MakeJoints()
	end)
1 Like

Is script.Parent a click detector?

it is (I need to type more to send this message)

  1. You’re using the wrong event, it should be MouseClick instead of MouseButton1Click.
  2. The first argument passed is always the player, so that would be how you get the name.

Just realized that it is a textbutton that is used to spawn the car

yes it is a textbutton (fnekmn)

1 Like

You should probably use a RemoteEvent for that if you’re wanting to detect when a UI Interface Event fires so that you can connect it from the client, onto the server to properly clone

Basically what a RemoteEvent is, is that it’s capable of handling client-server/server-client transportation easily and you can easily reference the Player that fired the Event

What you’ll need to do, is first create a RemoteEvent that’s inside the ReplicatedStorage, change your MouseButton1Click Event script to a LocalScript to fire onto the server, and create a new script inside ServerScriptService which will detect for those said “fired events”

--Client/LocalScript--

local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")

script.Parent.MouseButton1Click:connect(function() --MouseButton1Click has no parameters
    Event:FireServer() --We're firing this onto the server
end)
--Server Script inside ServerScriptService
local Event = game.ReplicatedStorage:WaitForChild("RemoteEvent")
local Mod = game.ServerStorage:WaitForChild("lambo1")     

Event.OnServerEvent:Connect(function(Player) --By default, the Player that fired the event is automatically passed in so you don't need to worry about that
	local clone = Mod:clone()
	clone.Parent = workspace
	clone.Name = Player.Name
    clone:MakeJoints()
end)

Also keep in mind that Lua is case-sensitive, so you have to properly correct in the right formatting/capitalization for it to work

1 Like