I am working on making a magic system into my game. To gain magics you open crates, when you open a crate it creates a value named after the magic you earned (if it is not created already). If you already own one, it increases the value by one. My plan is to make it so the value saves and when you join, it can put it in your inventory. The problem is that when I try to just save the value itself, it doesn't save.
The script I have:
local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerData") game.Players.PlayerAdded:connect(function(plr) local key = "key-" .. plr.UserId local Magics = Instance.new("Folder",plr) Magics.Name = "Magics" pcall(function() save = DataStore:GetAsync(key) end) if save then for i,v in pairs(save) do -- where the inventory would be set up end else local load = plr.Magics:GetChildren() DataStore:SetAsync(key, load) end end) game.Players.PlayerRemoving:connect(function(plr) local key = "key-" .. plr.UserId local load = {} for i,v in pairs(plr.Magics:GetChildren()) do table.insert(load,v.Value) end DataStore:SetAsync(key, load) end)
Am I trying to do the right thing, or is there a more efficient way of doing this?
If you help, thank you!
First of all, you should be using :Connect, as :connect is depreciated. Secondly, you could save each value to a table which includes its name and value, then save those tables into another that you save.
local skillfolder = *Insertfolder* -- Make sure you set the folder function SaveSkills(player) local MasterTable = {} -- create the main table to save the others into for _, skills in pairs(skillfolder:GetChildren()) do -- get all the skills local SkillsTable = {} -- individual skill table SkillsTable.SkillName = skills.Name -- set skill name in table SkillsTable.SkillValue = skills.Value -- set skill value in table MasterTable[#MasterTable + 1] = SkillsTable -- Get the total number of entries in the master table, then save current table as the the total + 1 print(SkillsTable.SkillName, SkillsTable.SkillValue) -- Print to insure proper saving end SkillDataStore:SetAsync(player.UserId, MasterTable) -- Save master table print("Skills Saved!") end
Then you could simply iterate over the main table when you load, and then create a new value and with the name and value of the saved skills.
function LoadSkills(player) local Skills = SkillDataStore:GetAsync(player.UserId) -- get data if Skills ~= nil then -- if there is data then for _, SkillData in pairs(Skills) do -- iterate master table local NewValue = Instance.new("NumberValue") -- create new value NewValue.Name = SkillData.SkillName -- name value NewValue.Value = SkillData.SkillValue -- change value NewValue.Parent = skillfolder -- parent it print(SkillData.SkillName, SkillData.SkillValue) -- print to insure proper loading end else if Skills == nil then -- if skills doesnt exist print("Nil!") end end
Obviously you would have to edit it a bit, but this should be the gist of it.