"Unable to cast Array" when using SetAsync

Hey! I am designing a system and game that is mostly based off of datastores and I have a situation where it 1, the function does not run in studio unless ran in the actual game, and 2, gives me this error:

image

I did some research and read that this can happen if you are using datastore async functions too often, but there is nothing specific on how I can avoid this or somehow go around it, and I need help coming up with another system to prevent this error and correctly save the data. These are the functions and variables.

local DataStoreService = game:GetService("DataStoreService")

local data = {
	players = {
		count = DataStoreService:GetDataStore("players"),
		byName = DataStoreService:GetDataStore("playersByName"),
		byId = DataStoreService:GetDataStore("playersById")
	}
	
}

function getPlayerCount()
	return data.players.count:GetAsync("amount")
end

function listDatastores()
	return DataStoreService:ListDataStoresAsync()
end

function getStoredValue(datastore, key)
	return DataStoreService:GetDataStore(datastore):GetAsync(key)
end

local currentAmount = getPlayerCount()

print(currentAmount)

function updatePlayerData(player)
	if not data.players.byId:GetAsync(player.UserId) then
		data.players.count:SetAsync("amount", getPlayerCount()+1)
		print(currentAmount)
		data.players.byId:SetAsync(tostring(player.UserId), getPlayerCount())
		print(getStoredValue("playersById", tostring(player.UserId)))
		data.players.byName:SetAsync(player.Name, getPlayerCount())
		print(getStoredValue("playersByName", player.Name))
	end
	print("success")
end

local Players = game:GetService("Players")

Players.PlayerAdded:Connect(function(player)
	updatePlayerData(player)
end)

Please don’t mind the condition of this code, I am only coming up with systems and I plan on polishing them up when they work correctly. Thank you!

1 Like