Dreary1
1
I can only put my gun away.
public bool IsEPressed = true;
void Update()
{
if (Input.GetKey(KeyCode.E) == true)
{
if (IsEPressed == false)
{
myAnimator.SetBool("IsEPressed", true);
}
else if (IsEPressed == true)
{
myAnimator.SetBool("IsEPressed", false);
}
}
well you never update the value of IsEPressed so it is always true
In addition you use GetKey which will trigger every frame so long the key is pressed. Unless you have really really reall fast fingers you will never be able to only trigger this once.
So lets try to improve your code:
public bool weaponDrawn = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.E)) //check if "E" key was pressed >THIS FRAME ONLY>
{
toggleWeapon();
}
}
private void toggleWeapon()
{
weaponDrawn = !weaponDrawn; // set the value of weaponDrawn to the inverse of itself (true to false and false to true)
myAnimator.SetBool("weaponDrawn", weaponDrawn); // directly set this value to the animator
}
i renamed the variable IsEPressed to weaponDrawn. One should always name variables in a way that they describe what they do. While this is also true for “IsEPressed” it is more fitting for the actual gameplay i think.
I also switched this name in the animator.
Let me know what you think or if something is unclear.
when using bools there are a few tricks you can use, you don’t need to use the equivalence operator == in an conditional and you can use the not operator ! to mean false, you do not need an else if, just else, the condition is implied, you source could be rewritten as:
if (Input.GetKey(KeyCode.E))
{
if (!IsEPressed)
{
myAnimator.SetBool("IsEPressed", true);
}
else
{
myAnimator.SetBool("IsEPressed", false);
}
}
Also you can also assign the bool variable to the animator and remove he conditions altogether:
if (Input.GetKey(KeyCode.E))
{
myAnimator.SetBool("IsEPressed", IsEPressed);
}
Then finally to answer your question bools can be toggled using the NOT ‘!’ operator.
someBool=!someBool;
This statement if the bool is true will set it to false and if it’s false it will set it to true.
So the final code is:
if (Input.GetKey(KeyCode.E))
{
isEPressed=!isEPressed;
myAnimator.SetBool(“IsEPressed”, isEPressed);
}
It’s the same answer as above, just wanted to explain some of the steps.