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

How to check a players inventory for an item?

Lets say I made a button that gives you a sword, and I want it to be if you already have a sword, the one you already have gets deleted and replaced by the new one. How could I do this?

2 answers

✓ Accepted answer
-- Script
local TextButton=script.Parent
local gui=TextButton.Parent
local player=gui.Parent.Parent
local newtool=game.ServerStorage.Sword2
--local cost,debounce=20,nil;
TextButton.MouseButton1Click:Connect(function(...)
	--if debounce or not player.leaderstats.Points.Value>=cost then return end 
	--debounce=true
	local char=player.Character
	local backpack=player:FindFirstChild"Backpack"
	local tool=(backpack and backpack:FindFirstChild("Sword1")
		or char and char:FindFirstChild("Sword1")
	)
	if tool then
		--player.leaderstats.Points.Value-=cost
		tool:Destroy()
		newtool:Clone().Parent=backpack
	end
	--wait(.5)debounce=false
end)

Solution

We would need a LocalScript, Script and a Remote Event which would be used to communicate between the client and server.

LocalScript

local Client = game.Players.LocalPlayer
local PlayerGui = Client:WaitForChild("PlayerGui")
local Button = PlayerGui.ScreenGui.TextButton
local RemoteEvent = game.ReplicatedStorage.RemoteEvent


local function OnButtonClick()
   RemoteEvent:FireServer()
end


Button.MouseButton1Click:Connect(OnButtonClick)

Script

local RemoteEvent = game.ReplicatedStorage.RemoteEvent
local Sword = game.ServerStorage.Sword


local function GiveSword(Player)
   if Player.Backpack:FindFirstChid("Sword") then
     Player.Backpack.Sword:Destroy()
     Sword:Clone.Parent = Player.Backpack
   else
     Sword:Clone.Parent = Player.Backpack
  end
end


RemoteEvent.OnServerEvent:Connect(GiveSword)

Extra info

If you want to hide something from the client put it in ServerStorage or ServerScriptService since they can't view what's inside, but the client won't have access to objects in these services. So, if you wanted to access something from inside of these services you can do it via remote event also make sure to validate the stuff coming through the remote event because an exploiter can fire it whenever they want.

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