- Home /
Make a boolean positive and then negative with same button
Hey all So I've looked a bit and haven't really found an answer, so here goes. I have a code ( in JS but help in C# works also) that starts an animation when the space key is pressed and I have that part working but I don't know how to make it so that when I press the space key again the animation will stop.
this is the relevant code
private var anim: Animator; //a reference to the animator component
function Awake()
{
//set up references
anim = GetComponent(Animator);
}
function Update()
{
var swing: boolean = Input.GetButton("Attack");
//Animate the player
Animating(swing);
}
function Animating (swing: boolean)
{
if(swing == true)
{
anim.SetBool("Sword01", true);
}
}
So yeah any help on how to make it set the boolean back to false by pressing the space button a second time would be awesome! The animator is already set up so when the boolean turns false the animation should stop. Thanks
Answer by jcv8000 · Apr 19, 2015 at 01:29 AM
function Update()
{
if (Input.GetButtonDown("Attack"))
{
anim.SetBool("Sword01", !anim.GetBool("Sword01"));
}
}
You might want to use "Input.GetButtonDown" as your code will flip the bool every frame as long as the button is held down.
Oh yeah I used the GetButtonDown function I guess I missed that in the post. And thank you both very much its working now! Is there any chance you could explain the part of the code? "!anim.GetBool("Sword01"));"
Sure. anim.GetBool("Sword01") returns the value of the animator boolean called "Sword01" that you were trying to originally set. Using a "!" means the opposite of that value. So that means it is setting the opposite of what it is.
Your answer
![](https://koobas.hobune.stream/wayback/20220613193456im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to check how many times an animation has played? 1 Answer
Add a bool to animator & activate by key press 1 Answer
how to turn animator on if bool = true 2 Answers
Error : Animator has not been initialized. UnityEngine.Animator:SetBool(String, Boolean) 1 Answer
how do i turn animator on from script if bool is true 2 Answers