Bool defaulting back to false

public class OnHit : MonoBehaviour
{
    private bool hasPackage;
    private void OnTriggerEnter2D(Collider2D col)
    {
        if (CompareTag("Package"))
        {
            Debug.Log("You have picked up the package!");
            hasPackage = true;
            Debug.Log(hasPackage);
        }
        if (CompareTag("Customer"))
        {
            Debug.Log(hasPackage);
        }
    }
}

I am decently proficient in Python, so this is really throwing me for a loop and I am stuck.
My bool value of hasPackage defaults back to false and I’m not sure why.

My variable seems to be in the correct position as to not be redefined upon the trigger being executed, but despite that this seems to return false, even though my code looks identical to the one in the video.

Any help would be appreciated, thanks!

I should mention that the first Debug.Log() is returning the correct value of true when triggering the package, but when running over the delivery point it always returns false.

Your code checks the object the script is on for the tag.

When the player enters a package trigger, the player - which has this script - checks its own tag. Is it a ‘Package’? No, it’s not. Is it the ‘Customer’? No, it’s not. Done, nothing happened. The package also has this script. So, it checks its own tag. Is it a ‘Package’? Yes, it is. Set hasPackage to true and Debug.Log that. Then, continues. Is the tag ‘Customer’? No, it’s not. Done. The package’s hasPackage has now been set to true.

Now, the player enters the customer’s trigger. Same thing for the player: It checks its own tag. Is it a ‘Package’? No, it’s not. Is it the ‘Customer’? No, it’s not. Done, nothing happened. The customer also has this script, so it runs the code, too. It checks its own tag. Is it a ‘Package’? No, it’s not. Is it ‘Customer’? Yes, it is. Debug.Log the hasPackage. But the customer’s hasPackage is false. Why would it be anything else?

You need to use col.CompareTag(...) for it to do what you expect.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms