When i try to print the CarModelName table in the table from GetStat it throws this error: ServerStorage.CarDataManager:27: attempt to index field '?' (a nil value). I have tried to fix it myself but couldn't.
OnCarPurchase
local CarDataManager = require(game.ServerStorage.CarDataManager)
local CarsAPI = require(game.ServerStorage.CarsAPI)
local Money --Where your money value is located
game.ReplicatedStorage.PurchaseCar.OnServerEvent:Connect(functi on(Player, CarModelName)
print(CarDataManager:GetStat(Player)[CarModelName])
end
CarDataManager (https://pastebin.com/5eQRzwZ1)
-- Set up table to return to any script that requires this module script
local CarStatManager = {}
local DataStoreService = game:GetService("DataStoreService")
local carData = DataStoreService:GetDataStore("carData")
-- Table to hold player information for the current session
local sessionData = {}
-- Function that other scripts can call to change a player's stats
function CarStatManager:ChangeStat(player, statName, value)
local playerUserId = "Player_" .. player.UserId
assert(typeof(sessionData[playerUserId][statName]) == typeof(value), "ChangeStat error: types do not match")
if typeof(sessionData[playerUserId][statName]) == "number" then
sessionData[playerUserId][statName] = sessionData[playerUserId][statName] + value
else
sessionData[playerUserId][statName] = value
end
end
function CarStatManager:GetStat(player)
return sessionData[player.UserId]["Owned"]
end
-- Function to add player to the 'sessionData' table
local function setupPlayerData(player)
local playerUserId = "Player_" .. player.UserId
local success, data = pcall(function()
return carData:GetAsync(playerUserId)
end)
if success then
if data then
warn(player.Name.." Is in car database.")
warn("Fetching data for player: "..player.Name)
-- Data exists for this player
sessionData[playerUserId] = data
else
warn(player.Name.." Haven't played before")
warn("Setting Default Values for Player: "..player.Name)
-- Data store is working, but no current data for this player
sessionData[playerUserId] = {
["Owned"] = {}
}
end
else
warn("Error: Couldn't fetch Car Data")
end
end
-- Function to save player's data
local function saveCarData(playerUserId)
if sessionData[playerUserId] then
carData:SetAsync(playerUserId, sessionData[playerUserId])
end
end
-- Function to save player data on exit
local function saveOnExit(player)
local playerUserId = "Player_" .. player.UserId
saveCarData(playerUserId)
end
-- Connect 'setupPlayerData()' function to 'PlayerAdded' event
game.Players.PlayerAdded:Connect(setupPlayerData)
-- Connect 'saveOnExit()' function to 'PlayerRemoving' event
game.Players.PlayerRemoving:Connect(saveOnExit)
return CarStatManager
