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

Help with RemoteEvent?

Asked by 8 years ago

This script fires when the player dies

respawnevent:FireServer(player)

This script is the response to the above script, but it doesn't work. How can I wait for the player to respawn to fire it?

respawnevent.OnServerEvent:connect(function(player)
    player.Character:MoveTo(game.Workspace.SpawnPart)
end)

1 answer

Log in to vote
1
Answered by 8 years ago

I think a practical way to accomplish this would be using the CharacterAdded event, then have it disconnect itself after the code inside the function has terminated. Here's an example:

Local script

 -- A thing to note with remote event calls, is that you don't actually need to pass the local player as an argument. By default, every remote event will automatically assign it's first argument to the player of the local script that called it.

respawnevent:FireServer()

Server script

-- Reference the spawn part
local SpawnPos = workspace.SpawnPart

respawnevent.OnServerEvent:connect(function(Client)
    -- create a variable that we can use to disconnect the CharacterAdded event
    local PlayerRespanwed

    -- Assign the CharacterAdded event to the variable
    PlayerRespanwed = Client.CharacterAdded:connect(function(Char)

        -- Wait for the player's torso
        local Torso = Char:WaitForChild("Torso") -- Get the torso

        -- Personally I think you should use CFrame on the Torso instead of MoveTo on the character, simply because MoveTo considers collision checks with other objects.

        -- Here I'm just setting the CFrame of the Torso to the Vector position of the spawn point. The "+Vector3.new(0,3,0)" is just to add some offset to the Y axis of the teleportation, to avoid the character getting stuck in the part.
        Torso.CFrame = CFrame.new(SpawnPos.Position+Vector3.new(0,3,0))

        -- Disconnect the event
        PlayerRespanwed:disconnect()
    end)
end)

A better suggestion?

Now, that's how that'd be done using remotes. However in this case, I don't think it's very necessary. Since we know this event should take place every time the player dies, we can simply avoid using remotes and just use this code in a server script:

local Players = game:GetService("Players")
local SpawnPos = workspace.SpawnPart

-- Just connect the CharacterAdded event to the player directly upon entry. And we only have to use it once.
Players.PlayerAdded:connect(function(Player)
    Player.CharacterAdded:connect(function(Char)
        local Torso = Char:WaitForChild("Torso")
        Torso.CFrame = CFrame.new(SpawnPos.Position+Vector3.new(0,3,0))
    end)
end)

Hope this helped, let me know if you have any questions.

Ad

Answer this question