Below is a finalized and optimized implementation for your request. This script will allow players to type /save # to save the hats they are wearing and /load # to retrieve and equip previously saved hats. Here's how you can achieve this in Roblox Lua (Luau):
Key Features
/save # saves all hats the player is currently wearing into a save slot.
/load # removes all the hats the player is wearing and equips the ones from the designated save slot.
- Utilizes Roblox's
DataStoreService to persist data between sessions.
Step-by-Step Script
Place this script in ServerScriptService.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local HatDataStore = DataStoreService:GetDataStore("HatDataStore")
-- Helper function to clear all hats from a player's character
local function clearHats(character)
if not character then return end
for _, item in pairs(character:GetChildren()) do
if item:IsA("Accessory") then
item:Destroy() -- Removes all accessories (hats specifically)
end
end
end
-- Helper function to save the IDs of the currently worn hats
local function getCurrentHats(character)
if not character then return {} end
local hatIds = {}
for _, item in pairs(character:GetChildren()) do
if item:IsA("Accessory") and item:FindFirstChild("Handle") then
local assetId = game:GetService("MarketplaceService"):GetProductInfo(item.Handle.MeshId).AssetId
table.insert(hatIds, assetId)
end
end
return hatIds
end
-- Helper function to load hats from saved data
local function loadHats(character, hatIds)
if not character then return end
for _, hatId in pairs(hatIds) do
-- InsertService loads the hat asset into the character
local hat = game:GetService("InsertService"):LoadAsset(hatId)
for _, item in pairs(hat:GetChildren()) do
if item:IsA("Accessory") then
item.Parent = character
end
end
end
end
-- Handling player's chat commands
Players.PlayerAdded:Connect(function(player)
-- Handling /save and /load commands
player.Chatted:Connect(function(message)
local character = player.Character
if not character then return end
-- Check if the message is a save or load command
local isSave = string.match(message, "^/save (%d+)")
local isLoad = string.match(message, "^/load (%d+)")
if isSave then
-- Save hats under the given slot number
local slot = tonumber(isSave)
if slot then
local hatIds = getCurrentHats(character)
local success, errorMessage = pcall(function()
local key = tostring(player.UserId) .. "-" .. tostring(slot)
HatDataStore:SetAsync(key, hatIds)
end)
if success then
player:SendNotification({ Title = "Success", Text = "Hats saved to slot " .. slot })
else
warn(errorMessage)
player:SendNotification({ Title = "Error", Text = "Failed to save hats." })
end
end
elseif isLoad then
-- Load hats from the given slot number
local slot = tonumber(isLoad)
if slot then
local success, hatIds = pcall(function()
local key = tostring(player.UserId) .. "-" .. tostring(slot)
return HatDataStore:GetAsync(key)
end)
if success and hatIds then
clearHats(character) -- Clear current hats
loadHats(character, hatIds) -- Equip saved hats
player:SendNotification({ Title = "Success", Text = "Loaded hats from slot " .. slot })
else
player:SendNotification({ Title = "Error", Text = "No saved hats in slot " .. slot })
end
end
end
end)
end)
Explanation of the Lua Script
-
Data Persistence with DataStore:
- Uses the player's User ID combined with the slot number (
/save 1 would be stored in PlayerId-1) to save the set of hat accessory IDs into the Roblox DataStore.
-
Chat Commands:
- When a player types
/save #, the script collects the IDs of all hats the player is wearing and saves them in the appropriate DataStore slot.
- When a player types
/load #, the script fetches the saved IDs from the DataStore, removes currently worn hats, and re-equips the saved ones.
-
Helper Functions:
clearHats: Removes all accessories from the player's character.
getCurrentHats: Gathers and returns the IDs of the hats the player is wearing.
loadHats: Takes an array of hat IDs, spawns the hats using InsertService, and sets them on the character.
-
Error Handling:
- Everything uses
pcall to handle issues like missing DataStore values or failed operations.
-
Notifications:
- The
player:SendNotification function sends a success or error message to the player directly.
How It Works
- When a player types
/save 1, the script extracts all the player's hats and saves them (by Asset ID) into the corresponding slot (e.g., "1") under their UserId key in DataStore.
- When a player types
/load 1, the script fetches the hat IDs from that slot and equips the hats by spawning them back onto the player's character.
Notes
- InsertService: InsertService requires the assets (hats) to be enabled for use in your game. If the hats are unavailable or not free, they won’t load properly.
- API Services Enabled: Ensure that API Services and data permissions are enabled for your game in studio (Game Settings > Security tab).
Now your players will be able to save and load hat presets dynamically!