Think of using DataStores as like your own personal, super big storage closet. This storage closet is special, because you can make keys, and a new storage door will be added when you make a key.
A key is a string. A key can be pretty much any string you want. If you want to save data for each player, you can use their UserId as a key. Normally you concatenate their UserId with another string, in case you want to use their UserId later to save data in a different 'storage closet'.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local headColorKey = "HeadColor_"
Players.PlayerAdded:Connect(function(player)
local key = headColorKey..player.UserId
end)
The key, in the code above, could be HeadColor_2353463, if the player who joined userId was 2353463. So they will have a special key, different from any else's.
Now we have to get a data store, and load data using GetAsync().
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local globalDS = DataStoreService:GetGlobalDataStore()
local headColorKey = "HeadColor_"
Players.PlayerAdded:Connect(function(player)
local key = headColorKey..player.UserId
local data = globalDS:GetAsync(key)
end)
If there isn't any data, we have to make the data and the data storage! AKA: Making the door. We do this using SetAsync().
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local globalDS = DataStoreService:GetGlobalDataStore()
local headColorKey = "HeadColor_"
Players.PlayerAdded:Connect(function(player)
local key = headColorKey..player.UserId
local data = globalDS:GetAsync(key)
if not data then
data = BrickColor.Random().Number
globalDS:SetAsync(key, data)
end
end)
This example is almost done! We load data, and if the data does exist we make it! Now we just have to use it.
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local globalDS = DataStoreService:GetGlobalDataStore()
local headColorKey = "HeadColor_"
Players.PlayerAdded:Connect(function(player)
local key = headColorKey..player.UserId
local data = globalDS:GetAsync(key)
if not data then
data = BrickColor.Random().Number
globalDS:SetAsync(key, data)
end
player.CharacterAdded:Connect(function(character)
local head = character:WaitForChild("Head")
head.BrickColor = BrickColor.new(data)
end)
end)
The above should make each players' head a random color once, and never change the color until the dataStore is reset, or the key is changed.
I hope my small tutorial helped!
1 comment
GetAsync is an expensive request so you should only do it once per thread. It's hard to help since the code makes no sense. http://wiki.roblox.com/index.php?title=Saving_Player_Data