Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 5 years ago
Edited by BlackOrange3343 5 years ago

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)`
0
I think he's trying to get the player through the Remote Event BlackOrange3343 2676 — 5y

2 answers

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

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)
Ad
Log in to vote
0
Answered by 5 years ago

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

0
Make this into a new question because this no longer has anything to do with this. BlackOrange3343 2676 — 5y

Answer this question