- Home /
Simple gun draw script not working
I'm writing a simple script for my FPS exercise so my character draws his weapon by clicking the right mouse button, and then puts it away with another click of the right mouse button. I have the first part working, but haven't managed to get the character to put away the weapon again.
The Javascript code I'm using is very simple, and linked to an animator.
#pragma strict
var Gun : GameObject;
var GunDrawn = false;
function Start () {}
function Update () {
if(GunDrawn && Input.GetMouseButtonDown(1)) {
Gun.GetComponent(Animator).SetBool("GunOut", false);
Gun.GetComponent(AudioSource).enabled = false;
GunDrawn = false;
}
if(!GunDrawn && Input.GetMouseButtonDown(1)){
Gun.GetComponent(Animator).SetBool("GunOut", true);
Gun.GetComponent(AudioSource).enabled = true;
GunDrawn = true;
}
}
When I run the game and right-click the correct animation plays and I can see the inspector marks the variable GunDrawn as "true", but when I right-click again nothing happens. Is this an issue with formatting? I'm sure there's a simple explanation and any help would be much appreciated.
Thanks!
Answer by Phantomized · Oct 21, 2014 at 08:51 AM
It's because when you set the gunDrawn to "false" in the first conditional statement, you allow it to jump right into the conditional statement after that where it will be set as true again instantly. This often happens when the same input will do different things depending on the situation. An easy way around this is to use a boolean like:
var pressed : boolean = false;
and then in the conditional statements ask for a condition such as
if(!pressed && GunDrawn && Input.GetMouseButtonDown(1)) {
pressed = true;
etcera...
and then at the end of the update method:
pressed = false;
You're welcome. :) If you are satisfied with the answer, please mark it as accepted, so people browsing the question queue can visually see that you don't need help with this topic anymore. :)
Your answer
Follow this Question
Related Questions
One use per level question 1 Answer
Get Component Errors 1 Answer
Help with gun scripting!? 1 Answer
Controlled Automatic Fire Rate (RayCasting) 2 Answers
separate script to reload. 0 Answers