Hello, Devs!
I recently written a code that uses profile service to save items you pick up, and it took me a while. I did everything in my power to write this and I finally did, but when I usually work like that I write really bad code, and of course I would like to improve each day so I’m here to ask you smart people to trash on my code a bit and explain how dumb I am.
Anyway this is how the code works:
-In an item i add a script that puts a tool name in an inventory table that saves using profile service.
-On a script in ServerScriptService, I get the players inventory and loop through that table and check if the name matches to a folder called “PossibleItems” in server storage, basically that folder contains all possible items a player can have.
-If the item matches, I clone it 2 times, place one in StarterGear and the second one in my BackPack.
Nothing too complicated but I neglected this part of scripting for a while now and now I’m struggling with it.
Thanks for taking your time to read this, I hope you won’t be too harsh on me.
--Script in a tool
local Players = game:GetService('Players')
local PlayerDataHandler = require(game.ServerScriptService:WaitForChild("PlayerDataHandler"))
local Tool = script.Parent
Tool.Touched:Connect(function(hit)
local player = Players:GetPlayerFromCharacter(hit.Parent)
if player then
local item = Tool.Parent.Name
PlayerDataHandler:Update(player, "Inventory", function(currentInventory)
table.insert(currentInventory, item)
return currentInventory
end)
Tool.Parent:Destroy()
end
end)
--Script inside ServerScriptService
local PlayerDataHandler = require(game.ServerScriptService:WaitForChild("PlayerDataHandler"))
local possibleItems = game:GetService("ServerStorage").PossibleItems
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
task.wait(5)
local inventory = PlayerDataHandler:Get(player, "Inventory")
for index, Item in pairs(inventory) do
local itemList = possibleItems:GetChildren()
for i, v in pairs(itemList) do
if v.Name == Item then
local newTool = v:Clone()
local newTool2 = v:Clone()
newTool.Parent = player.Backpack
newTool2.Parent = player.StarterGear
end
end
end
end)