Variable value keeps resetting without any reason (or at least I think so)

Hello everybody,
I wanted to make a double jumping function, but I got into trouble and couldn’t make it work …
so I tried to write the code chunk by chunk.
With this example, If the player press the key and have a Jump_Count > 0, he can perform the action, but what I discovered is that this Variable keeps resetting every time the whole function (Player_Jump_V3()) get called in the Update() method.
To clarify:

  • Jump_Count_Max, Jump_Cooldown are not yet used, because as I mentioned I am remaking the function all over again.
  • Deubugger() is my debugging function, just to display text and it doesn’t contain Jump_Count.
  • Jump() is the function that contains “Rigidbody.AddForce()”, and of course it does not contain Jump_Count
  • I commented out every Function in Update(), FixedUpdate().
  • I made sure that all these functions : OnTriggerEnter(), OnTriggerExit(), OnCollisionEnter(), OnCollisionExit(), do not use Jump_Count.
void Player_Jump_V3(float Jump_Power,Rigidbody RB,Vector3 Jump_Vector,int Jump_Count,int Jump_Count_Max,float Jump_Cooldown){
   
        Debugger("Jump(s) remaining: "+Jump_Count);
       
        if (Jump_Count > 0 && Input.GetKeyDown(Player.Player_Key_Binding.Jump_Key) ) {
                Jump(Jump_Power,RB,Jump_Vector);
                if (Jump_Count > 0) {
                    Jump_Count --;
                    Debugger("Jump(s) remaining: "+Jump_Count);
                }
        }
    }

Thank you.

What does your Update() look like? What are you passing into Jump_Count from Update()?

From what I see here, you are decrementing the local variable Jump_Count in this method and that’s it. If you have a field on your class, it’s not going to be touched by this code. You are only decrementing the local copy inside this method.

I am passing another, global variable as Jump_Count,
Also, Update() contains only Player_Jump_V3()

When you pass a value type such as “int” into a method, C# creates a copy of the variable. Your method argument “int Jump_Count” is a local variable only for this method. If you have another variable called Jump_Count in a higher scope, this local variable will “hide” it inside this method. When you change it inside the method, the changes will not be visible anywhere else in your program. If you want to modify a “global variable” (not sure what a global variable is, do you mean instance variable?), you should just use that variable directly.

In short: remove the Jump_Count parameter from your method, and use the global variable directly.

1 Like

More information about passing value-type parameters in C#: Method Parameters - C# reference | Microsoft Learn. Note:

Thank you.
Yeah, I meant Instance Variable.