- Home /
Aim only works while button is held down... how do I make it a toggle?
So I've got this script that I wrote a while back, and I had set it up to where the mouse button or the alt pos. key had to be held down in order for it to work. The script checks to see if the right mouse button (Fire2) is being held down, and if so it activates the Aim camera. If the mouse button (Fire2) is lifted, or GetButtonUp("Fire2"), then it deactivates the aim camera. I would like to alter this script by making it a toggle, rather than having to hold down the aim button. I've tried changing GetButtonUp to be GetButtonDown, so that it would need 2 clicks in order for it to activate/deactivate, but the script breaks every time I do that. Here's the working script:
var Aim : boolean = false;
var Cam : GameObject;
function Update () {
if(Input.GetMouseButtonDown(1)||Input.GetButtonDown("Fire2")) {
Aim = true;
if(Aim == true) {
Cam.active = true;
}
}
if(Input.GetMouseButtonUp(1)||Input.GetButtonUp("Fire2")) {
Aim = true;
if(Aim) {
Cam.active = false;
}
}
}
So any ideas as to how I can get this to work? BTW the only reason I have the || statements that say this button or that button, is because I couldn't get Fire2 to work at some point for some reason, so I just used MouseButton in combination with GetButton, just to be safe. Thanks!
EDIT: I've also tried adding a variable IsAiming, or just using the already available boolean variable Aim in order to see if the gun is already aiming, and if so then if the button is clicked then deactivate. I just can't seem to be able to implement it!
Answer by robertbu · Apr 13, 2014 at 10:03 PM
Try this:
#pragma strict
var Aim : boolean = false;
var Cam : GameObject;
function Update () {
if(Input.GetMouseButtonDown(1)||Input.GetButtonDown("Fire2")) {
Aim = !Aim;
Cam.SetActive(Aim);
}
}
Note this code is based on your current code that activates/deactivates the game object. GameObject.active is depriciated, so I'm using SetActive(). You may want to enable/disable the aiming script instead.
Thanks so much! Totally worked. $$anonymous$$y hero! Lol really, thanks. I've been trying to make it work for awhile. :D
Your answer
![](https://koobas.hobune.stream/wayback/20220613142638im_/https://answers.unity.com/themes/thub/images/avi.jpg)