My way to solve the "do I have a package"-problem

I did the same thing in the previous lesson. Did it like this:

void OnTriggerEnter2D(Collider2D other)

{
    if (other.tag == "Package")
    {
        Debug.Log("Package picked up");
        packageCounter++;
        Debug.Log("You have " + packageCounter + " packages.");
     }

    else if (other.tag == "Customer" & packageCounter > 0)
    {
        Debug.Log("Package delivered");
        packageCounter--;
        Debug.Log("You have " + packageCounter + " packages.");
    }

It works. What is the difference between using & and &&? (andandandand :>)

&& is a short-circuit, checking to see if x and y are the same and returning a true/false value
What this AND does is check the left side of the && and if it is true will check the right side. If it is false it will not check the right side.

bool isTrue = FunctionFalse() && FunctionTrue()
print(isTrue)

FunctionFalse(){
 print("False");
 return false
}
FunctionTrue(){
 print("True")
 return true
}

The && will check the FunctionFalse to see if it’s a true or false statement. Since it is false, it will not continue to check FunctionTrue and so assign the isTrue value to false.

So what we would see in our log would be
False
false

With the & even if something returns false, it’ll proceed to check the remaining statement.

bool true = FunctionFalse() & FunctionTrue()
print(true)

FunctionFalse(){
 print("False")
 return false
}
FunctionTrue(){
 print("True")
 return true
}

So it’ll go FunctionFalse(). Even though it is already getting false for our check, it’ll then proceed to check FunctionTrue(), before assigning the value of false.

What we would see in our log is:
False
True
false

In the case of your code, Even if it isn’t a customer we are colliding with, we are still checking to see if our package is greater than 0, but will not enter the if statement because of the first false

I recommend checking out: Boolean logical operators - C# reference | Microsoft Docs

Privacy & Terms