So, in my game i have a shop where players can buy items. When an item is bought the script checks if the player already owns the item, if the player does already owns the item it adds 1 to the value of the item, if the player doesn’t own the item the script creates a number value with the name of the item. My scripts saves new values crated inside the Inventory folder but i can not figure out how i could make it save the values of the items(values with the item name) inside that folder.
As you can see in the screenshot above i have a value named “Item1” created in the Inventory folder, the script will save the value(Item1) but i need help making it save the value of it
The script:
local DataStoreService = game:GetService(“DataStoreService”)
local InventoryDataStore = DataStoreService:GetDataStore(“TestingData”)
game.Players.PlayerAdded:Connect(function(player)
local Inventory = Instance.new("Folder")
Inventory.Name = "Inventory"
Inventory.Parent = player
local equippedItem = Instance.new("StringValue")
equippedItem.Name = "EquippedItem"
equippedItem.Value = "None"
equippedItem.Parent = player
local data = InventoryDataStore:GetAsync(player.UserId.."-item")
if data then
for i, itemName in pairs(data) do
local NewVal = Instance.new("NumberValue")
NewVal.Name = itemName
NewVal.Parent = player.Inventory
game.ReplicatedStorage.Events.SendData:FireClient(player, itemName)
end
else
print("no data found")
end
local equippedItemData = InventoryDataStore:GetAsync(player.UserId.."-equippedItem")
if equippedItemData then
equippedItem.Value = equippedItemData
game.ReplicatedStorage.Events.SetEquippedItem:FireClient(player, equippedItemData)
end
end)
local function SaveData(player)
if player:FindFirstChild(“Inventory”) then
local inventory = {}
for i, v in pairs(player.Inventory:GetChildren()) do
table.insert(inventory,v.Name)
end
local success, errorMessage = pcall(function()
InventoryDataStore:SetAsync(player.UserId.."-item", inventory)
end)
if success then
print("data saved")
else
print(error..errorMessage)
end
end
if player:FindFirstChild("EquippedItem") then
if player.EquippedItem.Value ~= nil then
local success, errorMessage = pcall(function()
InventoryDataStore:SetAsync(player.UserId.."-equippedItem",player.EquippedItem.Value)
end)
end
end
end
game.Players.PlayerRemoving:Connect(function(player)
SaveData(player)
end)
game:BindToClose(function()
for i, player in pairs(game.Players:GetPlayers()) do
SaveData(player)
end
end)
game.ReplicatedStorage.Events.BuyItem.OnServerEvent:Connect(function(player, item, price)
if player.Inventory:FindFirstChild(item) then
player.Inventory[item].Value = player.Inventory[item].Value + 1
print("Item already owned, No new value created")
else
print("Item not owned, New value created")
local NewItem = Instance.new("NumberValue")
NewItem.Name = item
NewItem.Value = 1
NewItem.Parent = player.Inventory
player.leaderstats.Money.Value = player.leaderstats.Money.Value - price
end
end)