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

Player is nil and i dont know how to fix it.?

Asked by 1 year ago

Hi, i want a GUI button to clone a gun from the server storage and parent it to the backpack of the player that clicked the button, but it doesnt work because i get an error that tells me that the player is nil (this script works completly fine in a part and a click detector) maybe it is a dumb question but i am really new

script :

function a(x)
    local Ak47 = game.ServerStorage.Ak47:Clone()
    Ak47.Parent = x.Backpack
end


script.Parent.MouseButton1Click:connect(a)

error:

  23:51:23.115  Players.watarod.PlayerGui.zabkashop.Frame.TextButton.Script:3: attempt to index nil with 'Backpack'  -  Server - Script:3

1 answer

Log in to vote
1
Answered by 1 year ago
Edited by T3_MasterGamer 1 year ago

It's because MouseButton1Click doesn't have a parameter, meaning x does not exist and will never be the player that clicked the GUI Button.

To get the player that clicked the button, it's best to switch from normal script to local script then use Players.LocalPlayer.

But wait, there's a problem! You can't access ServerStorage through a local script. You can use ReplicatedStorage to clone your weapon to the player. This is how you would do it.

local ak = game.ReplicatedStorage:WaitForChild("Ak47")
script.Parent.MouseButton1Click:Connect(function()
    local clone = ak:Clone()
    clone.Parent = game.Players.LocalPlayer.Backpack
end)

But you will notice a problem, you can't damage players with your weapon.

This is how you fix that:

Server script(not local script), place this in ServerScriptService

--Place your weapon in ReplicatedStorage. You will also need to create a RemoteEvent in ReplicatedStorage.

local ak = game.ReplicatedStorage:WaitForChild("Ak47")
game.ReplicatedStorage:WaitForChild("RemoteEvent").OnServerEvent:Connect(function(plr)
    local clone = ak:Clone()
    clone.Parent = plr.Backpack
end)

Local Script, place this inside your button

script.Parent.MouseButton1Click:Connect(function()
    for i,v in game.Players.LocalPlayer.Backpack:GetChildren() do
        if v.Name == "Ak47" then return end --This makes it so players will only get 1 Ak47 instead of multiple.
    end
    game.ReplicatedStorage:WaitForChild("RemoteEvent"):FireServer()
end)
Ad

Answer this question