I’m not too comfortable with using DataStoreService yet, and am trying to make it so when a player joins for the first time or does not have any data in their datastore, it creates data from a template, else it just loads the DataStore.
I have been unsuccessful in achieving this. Here is my code so far.
game:GetService("Players").PlayerAdded:Connect(function(player)
local playerKey = ("player_" .. player.UserId) -- Makes it easier to visualize that the ID belongs to a player.
local PlayerDataStorage = DataStoreService:GetDataStore(playerKey, "Needs")
player.CharacterAdded:Connect(function(character)
local success, playerNeeds = pcall(function()
PlayerDataStorage:GetAsync(playerKey)
end)
if success then
local tempNeeds -- Temporarily stores it in a variable until we save it
print(playerNeeds)
print(PlayerDataStorage:GetAsync(playerKey))
if playerNeeds == nil then
print(player.Name .. " has no need data. Creating data now...")
tempNeeds = {
-- {NEED , % },
{"Bladder" , 100},
{"Fun" , 100},
{"Hunger" , 100},
{"Social" , 100},
{"Energy" , 100},
{"Hygine" , 100}
}
AddAttributes(character, tempNeeds)
PlayerDataStorage:SetAsync(playerKey, tempNeeds)
else
tempNeeds = PlayerDataStorage:GetAsync(playerKey)
AddAttributes(character, tempNeeds)
end
else
warn(playerNeeds)
end
There is more code below but it is unrelated to DataStores. The method I used with the pcall is what I’ve seen in other scripts I’ve dissected, but playerNeeds returns nil every time, and from my knowledge of pcalls, it shouldn’t have an issue running the function.
I’ve tried searching the forum but have had no luck. Is there a good method to approach this with?