if (Input.GetKeyDown(KeyCode.W) && jumpAmount < StatsProp.PlStats[PlayerStats.MaxJumpAmount])
{
rbody.velocity = new Vector2(rbody.velocity.x, 8 / Time.timeScale);
jumpAmount += 1;
print("JA: " + jumpAmount);
}
This is the piece of code that doesn’t work properly.
I’m working on a 2D Survival - Adventure - Space Shooter - Action game (Don’t Die, or Project S.A.S.S.A.). On the simplest things I seem to fail.
The script should do this:
- I press the W key.
- The player jumps.
- jumpAmount increases by 1.
- It prints jumpAmount.
The player jumps just fine, but if I increase the max amount of jumps, let’s say, to 5, sometimes when I jump jumpAmount int increases by 2, or even 3 instead of 1. This reasults on my player jumping less than it should.
Is there an explanation on why is this happening? Is it that my keyboard is being detected twice sometimes, or am I writing it the wrong way?
I know that this is basic, and probabbly really obvious, but thanks in advance for any help.
The probability that incrementing an integer is not working properly is vanishingly small. It is far more likely that it is being incremented an extra time somewhere else or the code is being called more times than you actually think it is.
You can measure what is actually happening more accurately by logging both the before and after value:
var before = jumpAmount;
jumpAmount += 1;
var after = jumpAmount;
Debug.Log("before = " + before + " and after = " + after);
Assuming you aren’t in some weird pocket of the universe where things work differently from everywhere else, I would venture that after will always be before + 1. Whether there is another piece interfering or your code is being invoked too many times can be identified from whether or not before value on one like is always equal to the after value on one of its most-recent predecessor.
That is, if you jump once and get two log lines for it, then the code is being invoked too often. If two jumps show a “gap” in the jumpAmount, some other code is interfering with the value in a way you didn’t anticipate.
I get that too sometimes. Don’t know the “right” answer but sometimes it helps ( for me anyway) to add a bool and make it a condition - if I understand the problem correctly. Add a bool and make it true then back to false after adding the +1. Can’t hurt to try.Give it a shot and let me know if it works
if (Input.GetKeyDown(KeyCode.W) && jumpAmount < StatsProp.PlStats[PlayerStats.MaxJumpAmount])
{
rbody.velocity = new Vector2(rbody.velocity.x, 8 / Time.timeScale);
jumpIncrease = true;//added bool up top and set true
if(jumpIncrease == true){//added condition
jumpAmount += 1;
jumpIncrease = false;//turned off to maybe stop jumpAmount adding more than you want on single key stroke
print("JA: " + jumpAmount);
}