Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

DataStoreService - Data not saving on leave?

Asked by 4 years ago
local function SaveGameData(plr, dataToSet)
    local data
    if dataToSet then
        data = dataToSet
    elseif dataToSet == nil then
        data = Server[plr]
    end
    print(data, Server[plr], dataToSet)
    local success, err = pcall(function()
        return LocalData:SetAsync('UserID_' .. tostring(plr.UserId), data)
    end)
    if success then
        print(plr.Name .. ': Saved')
        Server[plr] = nil
    else
        error(err)
    end
end

When the player joins, everything works fine but on leave (data, Server[plr], dataToSet) are all printed nil.

Not sure how to fix this exactly.

0
ServerStorage.ModuleScript:27: Argument 2 missing or nil tharatas 0 — 4y

1 answer

Log in to vote
0
Answered by
JesseSong 3916 Moderation Voter Community Moderator
4 years ago
Edited 4 years ago

That's because you haven't used the function PlayerRemoving This event is used for when the players left the game And make sure you use EnableStudio Api

local DATA_STORE_NAME = "Config"
local DATA_STORE_SCOPE = "MyGameName"
local KEY_NEW_FEATURE = "NewFeatureEnabled"

local DataStoreService = game:GetService("DataStoreService")

local dsConfig = DataStoreService:GetDataStore(DATA_STORE_NAME, DATA_STORE_SCOPE)

local function checkFeature()
    local isFeatureEnabled
    local success, err = pcall(function()
        isFeatureEnabled = dsConfig:GetAsync(KEY_NEW_FEATURE)
    end)
    if success then
        print(KEY_NEW_FEATURE .. ": " .. tostring(isFeatureEnabled))
        if isFeatureEnabled == true then
            print("Feature is enabled!")
        elseif isFeatureEnabled == false then
            print("Feature is disabled!")
        elseif isFeatureEnabled == nil then
            print("Feature is not set!")
        else
            -- Some other value was found in this key
        end
    else
        print("Failed to load feature! Error: " .. tostring(err))
    end
    return success
end

local function onFeatureChanged(isFeatureEnabled)
    print("Feature toggled: " .. tostring(isFeatureEnabled))
end

-- Listen for changes
dsConfig:OnUpdate(KEY_NEW_FEATURE, onFeatureChanged)

local function setFeatureEnabled(isFeatureEnabled)
    local success, err = pcall(function()
        dsConfig:SetAsync(KEY_NEW_FEATURE, isFeatureEnabled)
    end) 
    return success
end

setFeatureEnabled(true)
checkFeature()
0
I've failed to include that I did use PlayerRemoving. This doesn't really help. tharatas 0 — 4y
0
Explain how it doesnt help. JesseSong 3916 — 4y
Ad

Answer this question