Variable resetting when the code loops

Hi,

Thank you in advance for any help.

The code below is simplified to recreate the issue.

private int fah = 0;

TheLoop();
    
void TheLoop ()
{
    for (int f = 0; f < 10; f++) 
    {
    	print(fah);
    	NewGuy (fah);
    }
}

void NewGuy (int fah)
{
    fah++;
}

I’m running a for loop that calls to a function in which a variable is tracking the number of game objects in a particular sequence. I need it to retain the value of the variable and continue to add onto it in the following loops, but my variable resets when it returns. Each time going back to 0. Why is that? Is there a way I can call to a function in a loop so that the variable doesn’t reset?

To be clear. This is just a simplified example. Simply putting the “fah++;” in the loop will not help me.

Thank you!

I think your problem is that you initialize fah as a member variable, but also as an argument variable in your NewGuy() method. So basically in NewGuy(), that variable is incremented, then destroyed and you’re left with the member variable named fah still at 0. try:

private int fah = 0;

 void TheLoop () {
     for (int f = 0; f < 10; f++) {
         print(fah);
         NewGuy ();
     }
 }
 
 void NewGuy () {
     fah++;
 }

It is because when you call a function, you pass a copy of the variable, not the actual variable. The easiest way to cope with this is to change NewGuy(fah) to fah = NewGuy(fah). Now in NewGuy function, change return type void to int, also, after editing the value, you have to return it. So add return fah; at the end of the function.

Also, better change the variable name inside the function to not get confused with which fah you are dealing with.

Also if you deal with multiple variables getting passed to a function, you will need to pass them by reference.