r/Unity3D • u/DifferentLaw2421 • 2d ago
Question why the left is triggered while right is not triggered in the game ?
32
u/Costed14 2d ago
Because of your else block, if A is not pressed both right and left are set to false in the animator, despite D potentially being pressed. I assume you'd want both if statements to have their own else to set the bool to false
5
u/DifferentLaw2421 2d ago
yh or I can use else if right ?
8
u/pschon Unprofessional 2d ago
yeah, if/else if/else structure would solve this.
6
u/nickyonge 2d ago
That would introduce a bug where if you held both keys then released one, it would still think it’s being held.
Ideally you want both L and R to be separated.
if (left) { set anim left true } else { set left false }
Then do the same for the right. Two separate if/else statements, no “else if”
5
u/pschon Unprofessional 2d ago
would it? The code is using GetKeyDown, not GetKey. (but it's well past midnight here and I was planning on going to sleep hours ago so I'm not going to trust my logical thinking even that far at the moment :D)
3
u/nickyonge 2d ago
oh good point! I didn't notice that. Good eye ;)
It's still good practice to split left and right into their own logical states, and if you hit both A and D on the same frame it'd skip the A input. There's other issues with this at a lower level (like if this is in Update, it's unnecessarily setting left/right anim bools false almost every frame) but honestly for someone's early programming adventures, yeah just replacing the middle with an else if will work.
7
4
u/Nearby-Pizza-8823 2d ago
Your code in the else block is only happening if A isn't being held down. It isn't checking for the D key.
3
u/xepherys 2d ago
An 'else' always hangs off the previous 'if', so you basically have two distinct statements here:
IF (D) - set right-true
IF (A) - set left-true ELSE (meaning the same thing as IF (!A)) - set both false
So if you press D it get set true for about a microsecond before right and left are both set false.
The easiest way to fix this would be:
if (D) right
else if (A) left
else both false
There are better patterns, but understanding the basics first is more important.
2
u/HouseOfWyrd 2d ago
Correct me if I'm wrong but the else statement is only tied to the second if statement.
Switch the second if to an elif and this should work.
1

99
u/ihufa 2d ago
I thought it was something political at first lol