I am finding it difficult to learn how to make a script where the script identifies a certain slot in the players inventory. Similar to what piggy uses for their keys etc…
Please, any help on how to find a certain slot and switch tools like piggy does?
I’am aware, basically, in piggy, you can collect only one item per time, if you grab other, it will throw the one you were using right now, letting you have only 1 inventory slot.
if you mean you want to find the index or key that corresponds with a certain value, then you can get the index this way.
function getIndex(value, array)
for k, v in pairs(array) do
if v == value then
return k end
end
end
tab = {"a",5,2,"str"}
print(getIndex("str", tab)) --> 4
print(getIndex(5, tab)) --> 2
if you want it so there can only be one item in the inventory, and when there’s more the previous one is removed, do this:
local Players = game:GetService("Players")
local player = Players.LocalPlayer
-- Connect to MouseClick
local inv = player:WaitForChild("Backpack")
if #inv:GetChildren() ~=0 then
return inv:GetChildren()[1]:Destroy()
end
print("no tools found ")
Connect the MouseClick event and then just add clone the other tool to the backpack
Use a ClickDetector’s .MouseClick event and from the player delete any instance that is under the player’s Backpack and add a new one.
local ExistingTool = Player.Backpack:GetChildren()[1]
if ExistingTool then
ExistingTool:Destroy()
end
-- Give the new tool to the player via their Backpack.
If you’re talking about how to replace the position of the new tool in your backpack to the old one you’re likely better off creating your own backpack system to do this.
There is one way I can think of doing it with Roblox’s current backpack UI but it will be very messy and horrible for performance so it is highly not recommended. You could possibly sort a table with the tool indexes before removing it and replace the old tool index with the new one, then set the parent of all the tools to nil on the server and set their parent back in order with the sorted table.