Save a Player Music Preference Safely thumbnail
0 views0 copies0 likes

Save a Player Music Preference Safely

Universal script

Copy it, then test it in your own Studio place.

DataStore Verified

Script code

24 lines · 0.9 KB
Download
local Players = game:GetService("Players")local DataStoreService = game:GetService("DataStoreService")local store = DataStoreService:GetDataStore("MusicPreferenceV1")local loaded = {}local function key(player) return "user:" .. player.UserId endlocal function load(player)	local ok, value = pcall(store.GetAsync, store, key(player))	if not player.Parent then return end	player:SetAttribute("MusicEnabled", value ~= false)	loaded[player] = ok or nilendlocal function save(player)	if not loaded[player] then return end	local enabled = player:GetAttribute("MusicEnabled") ~= false-- …open Get script for the full source

About this script

Use a published test place with Studio API access for this server Script. It loads a boolean MusicEnabled preference and saves it when the player leaves or the server closes. A failed load never writes a default over existing data. Wire your own validated settings control to the MusicEnabled attribute on the server. Use a separate data store name for early experiments.

Comments

Share what works, ask questions, or report an issue.

0

Log in to leave a comment.

No comments yet

Be the first to share your thoughts!

Raw Luau source

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local store = DataStoreService:GetDataStore("MusicPreferenceV1")
local loaded = {}
local function key(player) return "user:" .. player.UserId end
local function load(player)
	local ok, value = pcall(store.GetAsync, store, key(player))
	if not player.Parent then return end
	player:SetAttribute("MusicEnabled", value ~= false)
	loaded[player] = ok or nil
end
local function save(player)
	if not loaded[player] then return end
	local enabled = player:GetAttribute("MusicEnabled") ~= false
	local ok, err = pcall(store.UpdateAsync, store, key(player), function()
		return enabled
	end)
	if not ok then warn("Preference save failed", err) end
end
Players.PlayerAdded:Connect(load)
Players.PlayerRemoving:Connect(function(player) save(player); loaded[player] = nil end)
game:BindToClose(function()
	for _, player in Players:GetPlayers() do save(player) end
end)