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

How to check a players inventory for an item?

Asked by
pevdn 32
2 years ago

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

Log in to vote
1
Answered by 2 years ago
Edited 2 years ago
-- 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)

Ad
Log in to vote
0
Answered by 2 years ago
Edited 2 years ago

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.

Answer this question