简体   繁体   中英

Two If statements having a common bool problem

I have two if statements and two bools(bool1 and bool2) in my script.My script is like this-

using UnityEngine
using system.collection

public class example : MonoBehaviour
{
    public bool bool1;
    public bool bool2;

    void Update()
    {
        if (bool1 == true)
        {
            // play animation1
        }
        if (bool1 == true && bool2 == true)
        {
            // play animation2
        }
    }
}

I want only animation2 to play when both bools are true not both animation1 and animation2 together.

What should I do?

You need to rewrite your statement to:

if (bool1 == true && bool2 == true)
{
    // play animation2
}
else if (bool1 == true)
{
    // play animation1
}

Because your first statement is stronger, ie it's true when the second is true, that's why you need to reverse checking of your conditions.

Most developers would ommit the == true as it is unnecessary. If you want to check if something is false , you can just do !bool1 . Here is your code without the unnecessary == true 's:

if (bool1 && bool2)
{
    // play animation2
}
else if (bool1)
{
    // play animation1
}

You could go for a bit of nesting, with the added benefit that your bool1 only needs to be evaluated once:

if (bool1)
{
    if (bool2)
    {
        // play animation2
    }
    else
    {
        // play animation1
    }
}

You must change condition order.

void Update()
{
    if (bool1 && bool2)
    {
        // play animation2
    }
    else if (bool1)
    {
        // play animation1
    }  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM