I've been trying to update a value from a data store, what am I doing wrong?
Error: ServerScriptService.DataStore:11: attempt to index field '?' (a nil value)
Code initiating player data (Module Script):
local PlayerDataHandler_module = {} local module_Useful = require(game:GetService("ReplicatedStorage").Scripts.ModuleScripts.module_Useful) local DataStoreService = game:GetService("DataStoreService") local PlayerData = DataStoreService:GetDataStore("PLAYER_DATA") local Http = game:GetService("HttpService") local SessionData = {} local AUTOSAVE_INTERVAL = 120 function PlayerDataHandler_module:ReturnStat(Player, ItemName) return SessionData[Player][ItemName] end function PlayerDataHandler_module:AddToInventory(Player, ItemName, Amount) local PlayerDecodedInventory = Http:JSONDecode(SessionData[Player][1]) if module_Useful.FindItem(ItemName)then --< If the item name is in the _Replicated folder for _, v in pairs(PlayerDecodedInventory) do if v[1] == ItemName then --< Checks first value on table for item name Ex:) ["ItemName", Amount] v[2] = v[2] + 1 SessionData[Player][1] = Http:JSONEncode(PlayerDecodedInventory) end end end end function PlayerDataHandler_module:ChangeStat(player, statName, changeValue) if SessionData[player][statName] == nil or 0 then SessionData[player][statName] = 0 + changeValue else SessionData[player][statName] = SessionData[player][statName] + changeValue end end local function SavePlayerData(Player) --<Saves player data local key = "--<" .. Player.userId local Success, Message = pcall(function() PlayerData:SetAsync(key, SessionData[Player]) end) if not Success then print(Message) end PlayerData:SetAsync(key, SessionData[Player]) end local function SetupPlayerData(Player) --<Sets up player data local key = "--<" .. Player.userId local data = PlayerData:GetAsync(key) if not data then local Inventory = {} SessionData[Player] = {Http:JSONEncode(Inventory), Money = 0} PlayerData:SetAsync(key, SessionData[Player]) print("Player Set Up!") end SessionData[Player] = data end game.Players.PlayerRemoving:connect(function(Player) SavePlayerData(Player) SessionData[Player] = nil end) local function AutoSave() while wait(AUTOSAVE_INTERVAL) do for player, data in pairs(SessionData) do SavePlayerData(player) end end end game.Players.PlayerAdded:connect(SetupPlayerData) return PlayerDataHandler_module
Code from Script in ServerScriptService
local PlayerStatManager = require(game.ServerStorage.PlayerDataHandler) game.Players.PlayerAdded:connect(function(Player) local leaderstats = Instance.new("Model", Player) local MoneyValue = Instance.new("NumberValue", leaderstats) leaderstats.Name = "leaderstats" MoneyValue.Name = "Money" while wait(5) do PlayerStatManager:ChangeStat(Player, "Money", 3) MoneyValue.Value = PlayerStatManager[Player]["Money"] end end)
Update: Seems to happen whenever I request a stat from the DataStore