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

Tool not giving a tool from replicated storage (?)

Anyway I made a tool that has a secret feature, when pressing E It gives you a tool that lets you put people In jail, however It appears that I am attempting to Index nil with 'Backpack'???

Script (Local script):

local UserInputService = game:GetService("UserInputService")

UserInputService.InputBegan:Connect(function(key)
	if key.KeyCode == Enum.KeyCode.E then
		script.Parent.GiveItem:FireServer()
	end
end)

Script (Server script):

local tool = script.Parent
local ReplicatedStorage = game.ReplicatedStorage
local HiddenTools = ReplicatedStorage.SecretItems
local Player

game.Players.PlayerAdded:Connect(function(client)
	Player = client
end)

tool.GiveItem.OnServerEvent:Connect(function()
	local JailCell = HiddenTools["Jail Cell"]:Clone()
	
	JailCell.Parent = Player.Backpack
	tool.UserInputService:Destroy()
	script:Destroy()
end)

1 answer

That's because in this case the Player variable in ServerScript can be nil if game.Players.PlayerAdded isn't fired. i'm assuming you're trying to give the Hiddentool to the player who holds the tool. try replacing your ServerScript's script with this Script

local tool = script.Parent
local ReplicatedStorage = game.ReplicatedStorage
local HiddenTools = ReplicatedStorage.SecretItems

tool.GiveItem.OnServerEvent:Connect(function(Player)
	if tool.Parent = Player.Character then -- check if player holds the tool
		local JailCell = HiddenTools["Jail Cell"]:Clone()
		JailCell.Parent = Player.Backpack
		tool.UserInputService:Destroy()
		script:Destroy()
	end
end)

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