- Home /
 
How to toggle a key for a car to go forward or backward?
I Have two functions, one is when I want my car to go forward, and the other to go backward, If I Want to switch between them, I Keep Pressing on the "D" key. this is my code if(Input.GetKey(KeyCode.D)){ var direct = true; } if(Input.GetKey(KeyCode.R)){ var reverse = true; } if(direct){ goDirect(); } else if(reverse) { goReverse(); };
I Don't want to keep holding the "D" or The "R" button to make the car go in whatever direction "Continue doing the same function as long as I'm holding the key", I want to press once, I Pressed "D" so direct = true and the car continues to go forward unless I Press the "R" Button, It's like ON/OFF Button ?
Answer by HarshadK · Oct 01, 2014 at 02:50 PM
Instead of Input.GetKey use Input.GetKeyDown. Also don't declare direct inside if loop, put it outside any loop.
 // Declare this variable above any method
 var direct : bool;
 if(Input.GetKeyDown(KeyCode.D)){
     direct = true;
 }
 
 if(Input.GetKeyDown(KeyCode.R)){
     reverse = true;
 }
 
               It will work like you want.
@Harshad$$anonymous$$ get$$anonymous$$eyDown didn't work the way I Wanted, I Have to $$anonymous$$eep pressing.. pressing..pressing.. pressing..pressing.. pressing.. on the "D" Button
I want to press only one so it goes forward unless I Want to switch to reverse gear and I Press the "R" Button ONLY ONCE!!
and thank you for helping me, I really appreciate it :)
Check this:
 var direct : bool = true;
 var reverse : bool = false;
 
 void Update()
 {
     if(Input.Get$$anonymous$$eyDown($$anonymous$$eycode.D))
     {
         direct = true;
         reverse = false;
     }
     if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.R))
     {
         reverse = true;
         direct = false;
     }
     
     if(direct)
     {
         goDirect();
     }
     else if(reverse) 
     {
         goReverse();
     }
     
 }
 
                  It can also be done with only one variable:
 var direct : bool = true;
 void Update()
 {
     if(Input.Get$$anonymous$$eyDown($$anonymous$$eycode.D))
     {
         direct = true;
     }
     if(Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.R))
     {
         direct = false;
     }
     
     if(direct)
     {
         goDirect();
     }
     else
     {
         goReverse();
     }
     
 }
 
                 @Harshad$$anonymous$$ I Did what you said, but unity gives me this error in the console "Assets/Scripts/Car$$anonymous$$ove.js(8,15): BCE0018: The name 'bool' does not denote a valid type ('not found')."
Your answer
 
             Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Faux Gravity Prolem? #2 2 Answers
Help| Convert a javascript to C# 1 Answer