when my player touches this gun he should get it, and it works perfectly in Roblox studio but when I try it in an actual Roblox server I get this error
Workspace.Part.Script5: attempt to index field 'Local Player' (a nil value)
this is my code
local object = game.ServerStorage.Pistol local CloneObject = object:Clone()
local function onTouch(hit) CloneObject.Parent = game.Players.LocalPlayer.Backpack print('hi') end
script.Parent.Touched:connect(onTouch)
This isn't in a LocalScript. You can only access the local player from a Local Script.
Also, you cannot put this code in a local script as you index the ServerStorage and that is only accessible to the server, if FE is on.
Put this in a Script
local object = game.ServerStorage.Pistol local CloneObject = object:Clone() local function onTouch(hit) local player = nil for _,v in pairs(game.Players:GetPlayers())do if v and v.Character and v.Character:IsAncestorOf(hit)then player = v break end end if not player then return end CloneObject.Parent = player.Backpack print('hi') end script.Parent.Touched:Connect(onTouch)
EDIT: Fixed it there.
Scripts are global sided, and that's why there's no Local Player (except being in Roblox Studio)
You can try this:
local GUN_NAME = "Pistol" local OBJECT_TO_CLONE = game.ServerStorage:findFirstChild(GUN_NAME) function touch(part) if game.Players:findFirstChild(part.Parent.Name) then local player = game.Players:findFirstChild(part.Parent.Name) if player:findFirstChild("Backpack") then local CLONED_OBJECT = OBJECT_TO_CLONE:Clone() CLONED_OBJECT.Parent = player.Backpack end end end script.Parent.Touched:Connect(touch)
You are trying to get player with LocalPlayer which can only be used on Client's Scripts.
Try this instead, and I cleaned up some code:
local object = game.ServerStorage.Pistol local function onTouch(hit) local Player = game.Players:FindFirstChild(hit.Parent.Name) object:Clone().Parent = Player.Backpack print('hi') end script.Parent.Touched:connect(onTouch)