Hi, I've been trying to get the local player name into a function by getting it from a remote event but I could not because of indexing and return will not work. Here is my code:
local EnergyBar = `script.Parent function getPlayerName(localplayer) return localplayer end game.ReplicatedStorage.PlayerName.OnServerEvent:Connect(getPlayerName(localplayer)) EnergyBar.Activated:Connect(function() print("test") print(player.Name) local character = game.Workspace[player.Name] player.Character.Humanoid.Health = player.Character.Humanoid.Health + 100 player.Character.Humanoid.WalkSpeed = 21 wait(30) player.Character.Humanoid.WalkSpeed = 16 end)`
To do so make it a variable!
local function GetPlayerName(Playerobject) return Playerobject.Name end game.Players.PlayerAdded:Connect(function(Player) local PlayerName = GetPlayerName(Player) end)
return can return multiple arguments at once as well!
local function GetPlayerName(Playerobject) return Playerobject.Name, 'Hi!' end game.Players.PlayerAdded:Connect(function(Player) local PlayerName, msg = GetPlayerName(Player) end)
If you were to print msg and PlayerName they would print in the order you return it.
PS: In the script you provided, the first argument of a RemoteEvent is always player. It is automatically sent so on the client you don't need to send LocalPlayer
. So all you really had to do was:
RemoteEvent.OnServerEvent:Connect(function(Plr) -- Player is automatic on the client all you have to do is RemoteEvent:FireServer() print(Plr.Name) end)
Why will this code not work (The error is "07:58:58.864 - Players.jhawkes145.Backpack.EnergyBar.Script:4: attempt to index local 'Plr' (a nil value)")
`local EnergyBar = script.Parent
function getPlayerName(Plr)
return Plr.Name
end
game.ReplicatedStorage.PlayerName.OnServerEvent:Connect(getPlayerName())
EnergyBar.Activated:Connect(function()
print("test")
local player = getPlayerName()
print(player)
local character = game.Workspace[player]
player.Character.Humanoid.Health = player.Character.Humanoid.Health + 100
player.Character.Humanoid.WalkSpeed = 21
wait(30)
player.Character.Humanoid.WalkSpeed = 16
end)`