Hello, so I have this script attached to a gun my first person controller has. What it does is it plays an animation that zooms in and out the gun when the right mouse button is pressed. What i need it to do is when I first press the right mouse button, it plays the zoom animation on my gun and creates a variable called counter which has a int. value set to 1. Next, I need an if statement under function update that tests for is counter is = to 1. Then it tests if the right mouse button is clicked. If it is true, it will play a gun zoom out animation and reset counter to 0. I have a script below but I get the error, their is already a local variable, counter. The script is bellow in java script.
#pragma strict
var Gun : Transform;
function Update () {
if (Input.GetButtonDown("Fire2"))
{
var Counter : int = 1;
Gun.animation.Play("Gun Zoom");
}
if (Counter == 1)
{
if (Input.GetButtonDown("Fire2"))
{
var Counter : int = 0;
Gun.animation.Play("Gun Zoom Out");
}
}
}
Your counter variable is hidden inside of the if statements scope.
You need to define it outside and since its going to be used over more than one frame it should really have class scope.
#pragma strict
var Counter : int = 0;
var Gun : Transform;
function Update () {
if (Input.GetButtonDown("Fire2"))
{
Counter = 1;
Gun.animation.Play("Gun Zoom");
}
if (Counter == 1)
{
if (Input.GetButtonDown("Fire2"))
{
Counter = 0;
Gun.animation.Play("Gun Zoom Out");
}
}
}
I’m no JS programmer, but I suspect the error has to do with the fact that the VAR statment means: allocate and use this variable name. the INT part says what kind of variable it is. This is called a variable “declaration”
You probably want to declare the variable in the class, or script, OUTSIDE of your update function. This way, it will retain it’s assigned value between calls to update. (google the term “scope” for details)
Inside update, do not use the syntax to declare the variable, just use the syntax to assign a value to the (already declared) variable. probably something like Counter=0;