Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Making a datastore wait until Character loads?

I'm trying to make the script wait until when the player's character loads to work, I've tried to add code here but I don't know what I'm doing wrong, I may be missing an end but I don't know where to place it.

local datastore = game:GetService("DataStoreService"):GetDataStore("DataStore15")
game.Players.PlayerAdded:connect(function(player)
	    player.CharacterAdded:connect(function(char)
        while player:HasAppearanceLoaded() == false do
            wait()
	local leaderstats = Instance.new("IntValue")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local xd = Instance.new("IntValue")
	xd.Name = "example"
	xd.Parent = leaderstats
	xd.Value = 1

	local key = "user-" .. player.userId
	
	local storeditems = datastore:GetAsync(key)
	if storeditems then
		xd.Value = storeditems[1]

	else
		local items = {xd.Value}
		datastore:SetAsync(key, items)
	end
	end)

game.Players.PlayerRemoving:connect(function(player)
	local items = {player.leaderstats.example.Value}
	local key = "user-" .. player.userId
	
	datastore:SetAsync(key, items)
end)

1 answer

✓ Accepted answer

You either want to wait on the CharacterAdded event (player.CharacterAdded:Wait()) or use the while loop you have on line 4.

You should have the Output window open (and probably the Script Analysis one too); they would both tell you that you are missing an end to close the while loop (though they wouldn't tell the proper thing to close, as they can't know). If you keep the while loop, put it after the wait() command.

Using the event is better, but you should consider checking to see if the Character has already been loaded, just in case. (Otherwise, the script will wait for the player to respawn before continuing.)

You should also look up how to indent the script properly - it helps you see where an end is needed, if used properly - it would then be obvious where to put the end.

2 comments

0

Thank you for replying!! Can you please show me what you mean by using the event instead of what I have?

0

Ok i think I may have figured it out

This discussion is preserved as it was. New answers, comments, and votes are closed.