I am currently making a database system using module scripts like the one from the roblox articles page.
http://developer.roblox.com/en-us/articles/Saving-Player-Data
The script connects events to functions.
game.Players.PlayerAdded:Connect(setupPlayerData)
It does this for 2 events. PlayerAdded and PlayerRemoving.
However when I made my own version of this code. Using adaptations from the article page. Only the PlayerRemoving function fires. And not consistently either. Sometimes it prints the player removing message sometimes it doesn't. And the PlayerAdded function never fires, never outputs.
What have I tried?
I've tried debugging my own code using prints. This is how I know it doesn't consistently work for PlayerRemoving and how I know PlayerAdded doesn't work at all.
I've tried rewriting the code for executing the functions. I've turned them into 1 liners and achieved even worse results from doing so. What I mean by 1 liners (since I don't know the actual name)
game.Players.PlayerAdded:Connect(function(Player)
end)
Here is my code: (Any help is really appreciated I've been stuck on this for a while now!)
local PlayerStats_Manager = {}
local SessionStats = {}
local DataStoreService = game:GetService("DataStoreService")
local PlayerData = DataStoreService:GetDataStore("PlayerData")
function AddNewPlayer(Player)
print("add player")
local Key = Player.UserId
local DataStore
local Success, Error = pcall(function()
DataStore = PlayerData:GetAsync(Key)
end)
if not Success then
warn("Could not load data for ".. Player.Name .." ".. tostring(Error))
end
if Success then
print("Already had data on player stored")
SessionStats[Key] = DataStore
else
print("No data on player")
SessionStats[Key] = {
["Money"] = 0,
}
end
end
function PlayerRemoving(Player)
print("removing player")
local Key = Player.UserId
local Success, Error = pcall(function()
PlayerData:SetAsync(Key, SessionStats[Key])
end)
if Success then
print("Saved")
else
warn(Error)
end
end
function PlayerStats_Manager:ChangeStats(Key, Stat, NewValue)
print("player stat")
SessionStats[Key] = {
[Stat] = NewValue,
}
end
game.Players.PlayerAdded:Connect(AddNewPlayer)
game.Players.PlayerRemoving:Connect(PlayerRemoving)
return PlayerStats_Manager

3 comments
Are you sure you aren't requiring the module too late? If you require it after the first player joins, PlayerAdded won't fire for them
I'm pretty sure I'm not requiring the module too late.
Hi, I guess you could just make a script and place the module as a child of the script. The script would be used just to require the module, since you're already have a connection in the module.