This is the format I'm using for the dictionary to SetAsync()
local PlayerData = { ["Models"] = { }; ["Resources"] = { ["Money"] = 1; -- I want to update one of these ["Population"] = 12; ["Wood"] = 24; ["Stone"] = 64; ["Electric"] = 14; ["Water"] = 163; } }
This is the script I wrote to tell the server that the player's Data was changed
local Event = game.ReplicatedStorage.remoteevents.SaveData wait() for i, resource in pairs(game.Players.LocalPlayer:WaitForChild("Resources"):GetChildren()) do resource:GetPropertyChangedSignal("Value"):Connect(function() Event:FireServer(resource, resource.Value) end) end
Corresponding remote event script:
game.ReplicatedStorage.remoteevents.SaveData.OnServerEvent:Connect(function(player, resource, value) player.Resources[resource.Name].Value = value DataStore.UpdateResource(player, resource.Name, value) -- this is my own function inside of a modulescript end)
Lastly, here is my ModuleScript function:
function DataStore.UpdateResource(Player, Resource, Value) local DataStoreService = game:GetService("DataStoreService") local Data = DataStoreService:GetDataStore("PlayerData"):GetAsync("Player_" .. Player.UserId) DataStoreService:GetDataStore("PlayerData"):SetAsync(("Player_" .. Player.UserId)["Resources"][Resource], Value) -- Everything works fine up until here end
error:
15:05:37.513 - ServerScriptService.SaveDict.SaveData:15: attempt to index field 'Resources' (a nil value)
How do I access a single key inside of the dictionary "Resources" Which is inside of the dictionary "Player_26246132"?
any help is greatly appreciated!
Alright, I see your problem.
The value saved in each player is a dictionary - but the key is not (what you are trying to do currently is edit the specific key in the key).
What you do is save the entire dictionary after you have edited it:
local NewData = DataStoreService:GetDataStore("PlayerData"):GetAsync("Player_" .. Player.UserId) NewData["Resources"][Resource] = Value DataStoreService:GetDataStore("PlayerData"):SetAsync("Player_" .. Player.UserId, NewData)
Note: I believe saving dictionaries doesn't work that well. You'll need to convert it to another format first - people usually use JSON.
Saving:
NewData = HttpService:JSONEncode(NewData) DataStoreService:GetDataStore("PlayerData"):SetAsync("Player_" .. Player.UserId,NewData)
Loading:
local LoadedData = DataStoreService:GetDataStore("PlayerData"):GetAsync("Player_" .. Player.UserId) LoadedData = HttpService:JSONDecode(LoadedData)
Hope I helped!
~TDP