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

How do I give an item to a specific player only when the player joins and respawns?

Asked by 7 years ago

Whenever a player with a certain name joins, a script must execute and give the player a weapon and place it in the Backpack. But since it is not put in 'StarterPack' because it is only for one player, the weapon will be gone when the player respawns. So it will have to be given both when the player joins and respawns.

I have a script that tests if the player joins but I don't know what I have to do for it to execute when the player respawns:

sword = game.ServerStorage.GreenSword
local swordCopy = sword:Clone()

while true do
    local player = game.Players:FindFirstChild("Inscendio")

    if player then
        swordCopy.Parent = player.Backpack
    return end

    wait(1)
end

So I really need help with giving the weapon when the player respawns.

1 answer

Log in to vote
2
Answered by 7 years ago
Edited 7 years ago

It is not a good idea to use the players name as this can change, I would use UserId. We can use the CharacterAdded event which fires when the players character is added to the game.

This is a very basic example using the players name.

-- get the services
local plrSrv = game:GetService('Players')
local sword = game:GetService('ServerStorage'):WaitForChild('sword')

-- we are using a table so we can quickly check for the players name if not found it will be nil
-- this also allows us to quickly add new players without changing much code  

-- it would be best to use the players UserId but for this example I will use the player name
local allowedList = {
    ['Player1'] = true, 
    ['Player2'] = true
}

-- connect a player added event
plrSrv.PlayerAdded:connect(function(plr)
    -- connect a character added event
    plr.CharacterAdded:connect(function (charModle)
        if allowedList[plr.Name] then -- if the player is found in the list
            -- clone the tool but we also must wait for the backpack as it will take a small amount of time for it to be created
            sword:Clone().Parent = plr:WaitForChild('Backpack')
        end
    end)
end)

I hope this helps, please comment if you do not understand how / why this code works.

0
Thanks for helping. It was useful but my problem for now is that how do I make it so that it also gives when the player respawns. Inscendio 42 — 7y
0
Too many comments, makes it hard to read. Async_io 908 — 7y
2
CharacterAdded "Fired when a player's character spawns or respawns" so it will add the tool each time the respawn. User#5423 17 — 7y
1
I will do that automatically Inscendio. Async_io 908 — 7y
0
Oh okay thanks Inscendio 42 — 7y
Ad

Answer this question