Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

DataStoreService - Data not saving on leave?

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.

1 comment

0

ServerStorage.ModuleScript:27: Argument 2 missing or nil

1 answer

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()

2 comments

0

I've failed to include that I did use PlayerRemoving. This doesn't really help.

0

Explain how it doesnt help.

This discussion is preserved as it was. New answers, comments, and votes are closed.