- Home /
Unity Script help for on/off switch code.
I have been trying to create a code for entering and exiting a vehicle. I have been using the following:
var carCam :Camera; var walkCam : Camera; var on :boolean; function Update() { if(Input.GetButtonUp("action")) { on=true; car.GetComponent(carController).enabled=true; carCam.enabled=true; walkCam.enabled=false; } else { on=false; car.GetComponent(carController).enabled=false; carCam.enabled=false; walkCam.enabled=true; } }
when game starts, walkCam is on first. when i press the action key it switches to the car, but when i press action key again, it just stays on car. I am not the best at scripting and i have been searching for weeks as well as reading the scripting reference nad no luck, im not sure what im doing wrong. How can i make it so i can enter and exit a car?
Answer by Kleptomaniac · Apr 11, 2012 at 03:13 PM
You need to set up a toggle switch by negating a boolean flag each time your action button is pressed. Like so (cleaned up your script also):
var carCam : Camera;
var walkCam : Camera;
var on : boolean = false;
var toggle : boolean = false;
function Start () {
carCam.enabled = false;
car.GetComponent(carController).enabled = false;
}
function Update() {
if(Input.GetButtonUp(KeyCode.K)) {
if (!toggle) {
toggle = true;
on = true;
car.GetComponent(carController).enabled = true;
carCam.enabled = true;
walkCam.enabled = false;
} else {
toggle = false;
on = false;
car.GetComponent(carController).enabled = false;
carCam.enabled = false;
walkCam.enabled = true;
}
}
}
Next time, make sure to format your code correctly by highlighting the full code and pressing the 101010 button.
Hope that helps, Klep
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
C# Why Won't My GUI Layout Button Appear? 1 Answer
Multiple choice game not working!?! 1 Answer
UNEXPECTED TOKEN ) PLEASE HELP ME ;( 1 Answer