How do I access a Gui's text faster? (game.Players.PlayerRemoving and saving the Text in a datastore)

Here is my code below. I’ve encountered the problem where the script is not accessing a Gui’s text fast enough to save into a datastore in a game.Players.PlayerRemoving function. The client/player is already removed from the game before the script is able to access the Gui’s Text. Any ways to access the Gui’s text faster?

game.Players.PlayerRemoving:Connect(function(player)
	local generaldatatable = {player.PlayerGui:WaitForChild("QuestGui").Frame.MainFrame.Quest1.CoinAmount.Text, player.leaderstats["Coins"].Value}
	local success, error = pcall(function()
		DataStore:SetAsync(player.UserId, generaldatatable)
	end)
end)

Periodically save it. Pick some interval that wont max out your request budget.

What interval of seconds would you recommend to autosave?

Read this article.

Would 10 seconds be too little and lag the game out? Is 30 seconds better?

10 would work. 30 might be better though to leave room for other datastore requests.

1

use ordereddatastore [my recommendation]

2

ordered datastore can’t store strings, but can store tables

3

how to convert a string to a table of bytes

function STB(str)
 local res = {}
 for i = 1, #str do
  local by = string.byte(string.sub(str, i, i))
  res[#res+1] = by
 end
 return res
end

function BTS(tbl)
 local res = ''
 for _, by in next, tbl do
  local ch = string.char(by)
  res = res .. ch
 end
 return res
end

print(BTS(STB('among us drip')))

I don’t really know your entire setup but I’m gonna assume you set CoinAmount.Text for a player from the server at some point.

You can just store the CoinAmount in a playerData dictionary when you change the coins, and when the player leaves, read the CoinAmount from playerData instead of the GUI TextLabel

Something like this:

local playerData = {}
players.PlayerAdded:Connect(function(player)
    playerData[player.UserId] = {}
end)

-- whenever you change the coins for the player on their gui, it will also get stored in playerData dictionary
local function SetCoins(player, amount)
    local data = playerData[player.UserId]
    data.CoinAmount = amount
    player.PlayerGui:WaitForChild("QuestGui").Frame.MainFrame.Quest1.CoinAmount.Text = amount
end

game.Players.PlayerRemoving:Connect(function(player)
    local data = playerData[player.UserId]
	local generaldatatable = {data.CoinAmount, player.leaderstats["Coins"].Value}
	local success, error = pcall(function()
		DataStore:SetAsync(player.UserId, generaldatatable)
	end)
end)