Чтобы сохранить инструмент в Roblox с помощью службы DataStore, вы можете использовать различные методы. Вот несколько примеров кода:
Метод 1: использование GlobalDataStore
-- Server script
local DataStoreService = game:GetService("DataStoreService")
local toolDataStore = DataStoreService:GetGlobalDataStore()
function saveTool(player, tool)
local key = "Tool_" .. player.UserId
local success, error = pcall(function()
toolDataStore:SetAsync(key, tool)
end)
if not success then
print("Error saving tool: " .. error)
end
end
function loadTool(player)
local key = "Tool_" .. player.UserId
local success, tool = pcall(function()
return toolDataStore:GetAsync(key)
end)
if success then
return tool
else
print("Error loading tool: " .. tool)
end
end
-- Usage example
game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
local tool = loadTool(player)
if tool then
tool.Parent = player.Backpack
else
tool = -- create your tool here
tool.Parent = player.Backpack
saveTool(player, tool)
end
end)
end)
Метод 2: использование OrderedDataStore
-- Server script
local DataStoreService = game:GetService("DataStoreService")
local toolDataStore = DataStoreService:GetOrderedDataStore("ToolData")
function saveTool(player, tool)
local key = "Tool_" .. player.UserId
local success, error = pcall(function()
toolDataStore:SetAsync(key, tool)
end)
if not success then
print("Error saving tool: " .. error)
end
end
function loadTool(player)
local key = "Tool_" .. player.UserId
local success, tool = pcall(function()
return toolDataStore:GetAsync(key)
end)
if success then
return tool
else
print("Error loading tool: " .. tool)
end
end
-- Usage example
game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
local tool = loadTool(player)
if tool then
tool.Parent = player.Backpack
else
tool = -- create your tool here
tool.Parent = player.Backpack
saveTool(player, tool)
end
end)
end)
Способ 3: использование модуля DataStore2 (стороннего модуля)
-- Server script
local DataStore2 = require(1234567890) -- Replace with the DataStore2 module ID
function saveTool(player, tool)
local key = "Tool_" .. player.UserId
DataStore2(key):Set(tool)
end
function loadTool(player)
local key = "Tool_" .. player.UserId
return DataStore2(key):Get()
end
-- Usage example
game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
local tool = loadTool(player)
if tool then
tool.Parent = player.Backpack
else
tool = -- create your tool here
tool.Parent = player.Backpack
saveTool(player, tool)
end
end)
end)