You can write your topic however you want, but you need to answer these questions:
-
What do you want to achieve? Keep it simple and clear!
I want to get this piece of code working for a game I am working on. -
What is the issue? Include screenshots / videos if possible!
The issue is that no data is being saved at all and when the player loads and tries to retrieve data, it comes to be nil. -
What solutions have you tried so far? Did you look for solutions on the Developer Hub?
I have tried looking through the dev forum, watching youtube videos on data stores, and trying different methods of data saving.
-- Variables
local DataStoreService = game:GetService("DataStoreService")
local SaveData = DataStoreService:GetDataStore("SavedDataHotBar")
-- Functions
local function saveData(plr)
local hotBarData = {
["HotBarSlots"] = {}
}
local playerGui = plr.PlayerGui
local HotBarUI = playerGui:FindFirstChild("PlayerUI"):FindFirstChild("HotBar")
local SlotsTable = {HotBarUI.MainSlot, HotBarUI.SubSlot.SlotOne, HotBarUI.SubSlot.SlotTwo}
for _, v in pairs(SlotsTable) do
local slotName = v.Name
local slotData = {}
local slotNumber = v:FindFirstChild("NumberValue").Value
if not hotBarData["HotBarSlots"][slotName] then
hotBarData["HotBarSlots"][slotName] = {
slotNum = slotNumber,
data = slotData
}
else
hotBarData["HotBarSlots"][slotName].slotNum = slotNumber
end
end
local success, error = pcall(SaveData.SetAsync, SaveData, plr.UserId, hotBarData)
if not success then
warn("Failed to save data for player " .. plr.Name .. ": " .. error)
end
end
-- Events
game.Players.PlayerAdded:Connect(function(player)
local success, hotBarData = pcall(SaveData.GetAsync, SaveData, player.UserId)
if success and hotBarData ~= nil then
local playerGui = player:WaitForChild("PlayerGui")
local HotBarUI = playerGui:WaitForChild("PlayerUI"):WaitForChild("HotBar")
local SlotsTable = {HotBarUI.MainSlot, HotBarUI.SubSlot.SlotOne, HotBarUI.SubSlot.SlotTwo}
for slotName, slotInfo in pairs(hotBarData["HotBarSlots"]) do
local slotNumber = slotInfo.slotNum
local slotData = slotInfo.data
if HotBarUI:FindFirstChild(slotName) and HotBarUI[slotName]:FindFirstChild("NumberValue").Value == 0 then
HotBarUI[slotName]:FindFirstChild("NumberValue").Value = slotNumber
end
end
else
if not success then
warn("Failed to retrieve data for player " .. player.Name .. ": " .. hotBarData)
end
end
print(hotBarData)
end)
game.Players.PlayerRemoving:Connect(function(plr)
saveData(plr)
end)
After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!
-- This is an example Lua code block
Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.