I wanted to create an array with a name such as "currency_array" which would include all the currencies and then create resource's depending on how many values there are inside the array and then also loading and saving those values. But how would I go about making this?
Would this code work for you? An example of how to use it is at the bottom.
(Needs to placed within a server context):
-- Sets up a "hash" map of player IDs and player objects
-- to allow for quick and easy access of a player object
-- when given that player's id
local playerMap = nil
function CreatePlayerMap()
playerMap = {}
for _, player in Game.GetPlayers() do
playerMap[player.id] = player
end
end
-- Retrieves a player from the "playerMap" hash map
function GetPlayer(playerID)
return playerMap[playerID]
end
-- Set the player's resources to the values in the "currency_array"
function SetPlayerCurrencyFromCurrencyArray(player, array)
for currencyType, amount in pairs(array) do
-- if the player does not have this currency type as a resource, add
-- this currecny type as a resource
if(player:GetResource(currencyType) == nil) then
player:SetResource(currencyType, amount)
end
end
end
-- Updates one player's currency
function UpdatePlayerCurrency(playerID, data)
CreatePlayerMap()
for currencyType, amount in pairs(data) do
-- Assign resource amounts to the player
GetPlayer(playerID):SetResource(currencyType, amount)
end
end
function LoadPlayerCurrency(player)
-- Get the data from storage
local data = Storage.GetPlayerData(player)
if(data ~= nil) then
UpdatePlayerCurrency(player.id, data)
end
end
-- save all player resources
function SavePlayerCurrency(player)
Storage.SetPlayerData(player, player:GetResources())
end
--Example of how to use below:
currency_array = {gold=0, platinum=0}
--Load a palyer's currecy data when they connect
function OnPlayerConnected(player)
-- Load values of prexisting currencies
LoadPlayerCurrency(player)
-- Give players the currencies listed in the "currency_array"
SetPlayerCurrencyFromCurrencyArray(player, currency_array)
-- Save the player's currency data
SavePlayerCurrency(player)
end
Game.playerjoinedEvent:Connect(OnPlayerConnected)