- Home /
I'm having trouble setting a bool.
I'm trying to write a script where the player presses "Q" to grab an object. When the player presses "Q" again, the object is released. Here is a simplified version of my script:
void Update()
{
if (Input.GetKeyUp(KeyCode.Q) && !isGrabbing)
{
GrabObject();
isGrabbing = true;
}
if (Input.GetKeyUp(KeyCode.Q) && isGrabbing)
{
ReleaseObject();
isGrabbing = false;
}
When I press "Q" the player grabs the object and immediately releases the object. It seems like both if statements are being activated at the same time. When I use two different Key Codes for grab and release, it works fine. This is why I don't think the bools are acting right. Any help is appreciated. Thank you.
Answer by QKlon · May 28, 2018 at 02:29 AM
Of course the logic is: Mark isGrabbing true, then check if it really is true and immediately make it false again.
Try something like:
if ( Input.GetKeyUp(KeyCode.Q) )
if( isGrabbing = !isGrabbing )
GrabObject();
else
ReleaseObject();
Explaination:
You want only to do something, if Q is pressed.
Then you reassign 'NOT isGrabbing' (inverted) as new value to isGrabbing (i.e. you toggle the value first)
and immediately check the new state.
You call conditionally one of the methods.
As a bool value toggle you could also write isGrabbing ^= true
. That's the XOR assignment operator, i.e. the short form of isGrabbing = isGrabbing ^ true
.
Answer by jim3878 · May 28, 2018 at 03:19 AM
you just need to add "else" like this:
if (Input.GetKeyUp(KeyCode.Q) && !isGrabbing)
{
GrabObject();
isGrabbing = true;
}else if (Input.GetKeyUp(KeyCode.Q) && isGrabbing)
{
ReleaseObject();
isGrabbing = false;
}
because when you press "Q" when object is not grabbing it will match first expression
if (Input.GetKeyUp(KeyCode.Q) && !isGrabbing)
{
GrabObject();
isGrabbing = true;
}
and set isGrabbing to true. Then ,program will go to second expression
if (Input.GetKeyUp(KeyCode.Q) && isGrabbing)<<isGrabbing was just set to true.
ReleaseObject();
isGrabbing = false;
}
It will match seconds expression too. so Adding "else" will make sure that "Input.GetKeyUp(KeyCode.Q)" will not run twice.
Your answer
Follow this Question
Related Questions
Mouse click IF not checking properly 0 Answers
What am I doing wrong with this bool? 3 Answers
How Do I check if a Bool was True a few moments ago 2 Answers
Could use some help on making my runaway/chase/follow/patrol script cooperate with each other 1 Answer
Scavenger Hunt List Bools Question 1 Answer