Counting Up/Down with ArrowKeys wont work

Hey Guys,
i need some help with this:

var SelectedPack : float = 0;

function Update () {	

print(SelectedPack);
	
if(Input.GetKeyDown(KeyCode.RightArrow)){
	if(SelectedPack != 3){
		SelectedPack ++;
		print(SelectedPack);
	}
}
		
if(Input.GetKeyDown(KeyCode.LeftArrow)){
	if(SelectedPack != 0){
		SelectedPack --;
		print(SelectedPack);
	}
}
}

I have this script attached to the camera and probably im just dumb but it is kind of strange, what happens:

First SelectedPack is 0
if i press RightArrow it counts up
if i press Left Arrow it counts down

Everything normal so far.
But if i now press RightArrow nothing happens.
So it wont count a number i have reached 2 times before.

Has anybody a solution for my Problem? I was messing around with it quite a while but i didnt found any mistakes.

Thanks for your help, and sorry for my bad english im actually German.

Your code works fine...???

Thats the thing! The code looks as if it would work but it doesnt print the numbers correctly. Maybe its a bug?

Thanks for your help guys! It tested it once again by changing sprites and the sprites changed perfectly, but the console still counts wrong and i dont now why. It works now for me, but why does the console still print shit?

2 Answers

2

I copy-pasted your code, and it does exactly what it’s supposed to. You can count up to 3 and down to 0 as many times as you want.

In your console, do you have “Collapse” marked? That’ll make identical debugs fold into one, so that could be causing you confusion. If not, there’s something else going on, but it’s not in the script you posted.

You may wish to double check that:

  • Your script is attached to a scene object
  • Both your script component and the object carrying the script are enabled

If that didn’t help, try using Mathf.Clamp() to keep the value between 0 and 3:

var SelectedPack : float = 0;

function Update () {

    if(Input.GetKeyDown(KeyCode.RightArrow)){
        SelectedPack ++;
    }

    if(Input.GetKeyDown(KeyCode.LeftArrow)){
        SelectedPack --;
    }

    SelectedPack = Mathf.Clamp(SelectedPack, 0, 3);
    print(SelectedPack);
}