Need help with DataStore2

This is how I have my code:

DataStore2 = require(game.ServerStorage:WaitForChild('DataStore2'))

local LvlData = DataStore2('Lvl',Player)

Lvl = LvlData:Get(1)

print('GOT LVL'..Lvl)

LvlValueObj = script.Parent -- NumberValue Object

LvlValueObj.Value = Lvl

LvlValueObj.Changed:Connect(function()
	LvlData:Set(LvlValueObj.Value)
end)

I know some people are going to hate on me for using a NumberValue object.
To those people: no u

Anyway, this is the problem:
The data won’t save.

image
I have a NumberValue object under StarterCharacterScripts and this script inside said NumberValue object.

I know the module itself receives the info because the Level value gets set to the same number once the player resets their character. Despite this, once the player leaves the game and rejoins, their data is reset.

It’s possible this is an issue of how you only ever use DataStore2 in a StarterCharacterScript. If I add :Save(), then when I leave and come back it works fine.

I think this is the sequence of events that happens:

  • DataStore2 is required, not used anywhere else
  • Player leaves, the script is destroyed
  • The script is destroyed, the only reference to DataStore2 is destroyed, and so the code to save when a player leaves never runs

Try moving your code out somewhere else or just have something else use DataStore2, such as in ServerScriptService.

3 Likes

This seems to be what is happening.

I put this script inside ServerScriptService

DataStore2=require(game.ServerStorage:WaitForChild('DataStore2'))

p = game.Players:WaitForChild('dispeller')

while wait() do
	data = DataStore2('Lvl',p)
end

This made it so that Levels save but nothing else.
I guess I’ll have to rewrite things to be inside ServerScriptService instead.