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

How do I get a variable from a function connected to an event into another function?

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)`

1 comment

0

I think he's trying to get the player through the Remote Event

2 answers

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)`

1 comment

0

Make this into a new question because this no longer has anything to do with this.

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