Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why am I getting this error? It says 'Local Player' (a nil value)

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)

2 comments

0

How does it know what you want LocalPlayer to be?

0

You need a local script. You can't get to a local player through a normal script.

3 answers

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.

2 comments

0

now there is no error but also I don't get the gun

0

I edited it and it should work.

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)

3 comments

0

findFirstChild is deprecated; use FindFirstChild instead.

0

http://wiki.roblox.com/index.php?title=API:Class/Instance on "Functions" click "Show Hidden members" and it appears there.

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)

2 comments

0

What if he has another part hitting this part? :) My code above is checking that.

0

Welp, the dev isn't there yet.

This discussion is preserved as it was. New answers, comments, and votes are closed.