0

I am working on a game in Unity 2018.2.5f1. I have it setup where in a level you can collect coins placed around the level. I also have GUI label setup to count the coins you have collected. Then, in my main menu I have setup, There is another GUI label that is going to show how many coins you have collected throughout you playing. The problem is, I have been searching for a long time on how I can take the Level coin counter GUI label and add it to the main menu Coin counter GUI label. Below is the C# code for this (It really is not a lot of code).

public GUIStyle COINStyle; 

private void OnGUI()
{
    GUI.Label(new Rect(10, 10, 100, 20), "Coins : " + coins, COINStyle);
}

2 Answers2

0

At the start of the game, set a prior-to-level coin counter:

int alreadyGotCoins = 0; 

Then, at the end of each level success, update it with how many coins were collected before resetting the level coin counter:

alreadyGotCoins = alreadyGotCoins + coins;
coins = 0;

And then, on the main menu UI display the sum of the current level + prior coin counts:

GUI.Label(new Rect(...), "Total coins : " + (coins + alreadyGotCoins), mainMenuCoinStyle); 
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
  • What exactly should I do to "update" it. I don't what I am supposed to update or how I am supposed to update it. –  Oct 23 '18 at 22:39
  • You haven't shared enough of your code for me to give you an exact line to put in your code. `alreadyGotCoins = alreadyGotCoins + coins;` does the update to `alreadyGotCoins`. You need to put in variables/references that make sense for your code. It might look more like `gameManager.alreadyGotCoins = gameManager.alreadyGotCoins + gameManager.levelCoins`. I have no idea what your code looks like outside of the 3 lines in your question, but this answer is meant to broadly tell you how to go about solving your question regardless of your exact code structure. – Ruzihm Oct 23 '18 at 22:47
  • @Sam If you need help getting variables from other scripts, take a look at [this](https://stackoverflow.com/questions/25930919/accessing-a-variable-from-another-script-c-sharp) question. – Ruzihm Oct 24 '18 at 15:58
0

the way i have implemented this in the past was with tags. i would have a global variable class that stores all my variables, and use DontDestroyOnLoad(this) in its Awake() method. then i tag it "Global"

then i can do something like:

GlobalVariables gvar =GameObject.FindObjectWithTag("Global").GetComponent<GlobalVariables>(); 

in your menu class, and then use it to grab your stuff, like:

   int newcoins = gvar.coinscollectedlastlevel;
   gvar.coinscollectedlastlevel=0;
   coins= coins + newcoins;
Technivorous
  • 1,682
  • 2
  • 16
  • 22