Assigning data from a template to a Data Store when a player joins for the first time

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?

2 Likes

When a player does not have data, you usually do this
For example

Variable.Value = PlayerDataStore:GetAsync(player.UserId, Variable.Value) or 1

The 1 represents what the player will get if they have no data

Try testing it on another script

1 Like

This worked perfectly, thank you.

1 Like

@Jazoo1 No Problem my friend, Enjoy!

1 Like