Total Coins Collected

Hi, i’m new in Unity just started last December and i have a basic scripting knowledge in C#. I’m creating a game and already in the process of saving and retrieving game data, i’m having an issue regarding getting the total coins collected using an array. Attached is the simple logic image that i want to use in my game. I want to get all the coins that i have collected in every level and use it to buy some items in my store. I hope you can help me with my project. Thanks in advance.

Simply add them together?

1 Like

For Question 1 (in your image), as Antypodish said, just sum them together. You can easily do this using loops. If you did not yet look into loops, then you should immediately do this since they are kind of basic and increadibly useful for all kinds of things. You would sum up the total amount of coins like so:

totalCoins = 0;
for(int i = 0; i < coins.Length; i++){
    totalCoins += coins[i];
}

For convenience you could wrap this into a method, put in the int[ ] as parameter and return the sum.

As for Question 2:
This should be decided by the individual level completion. Not sure how you handled this, but i would have each level remember the coins collected internally. Then, if it’s more coins than the previous “highscore” you would write it to the array, otherwise not. This guarantees that only your highscores are in the coins array. You would then make the coins array persist between scenes and load it between sessions, thus always have the data in it available. Then each time you call Sum(coins) you will receive the total amount of coins.

One more tip, since you mentioned spending these coins in some shop. You will need to figure out how many coins you have available. If you have X coins and spend Y (Y<=X) you wouldnt want the user to still be able to spend X coins. The easiest way to save this with your setup would be to remember the spendCoins amount. Each time something is purchased, you add the price to this variable and save it (best using PlayerPrefs). Now when you need to calculate / display the available coin count you simply calculate totalCoins-spendCoins and are done with it.

Hope this helps!

1 Like

Thank you so much. This solve my problem. I’m also keeping a note regarding spending coins in the shop.

        if (gameData != null)
        {
            for (int i = 0; i < gameData.saveData.coins.Length; i++)
            {
                coinsCollected += gameData.saveData.coins;
            }
        }
        coinsCollectedText.text = "" + coinsCollected;