if with multiple clauses problem - C#

Hi,

I am beginning with C# scripting in unity and one thing just made me wonder, I had the following code:

if ((hit) & (hit.collider) & (hit.transform) & (hit.transform.gameObject)&(hit.transform.gameObject.tag=="Toy")) {
// Do something
}

So in general, I was checking if hit it not null, if hit colliders is not null, if hit transform isnt null, if gameobject isnt null and then checking the gameobject tag. And the code would throw NullReference error when the hit.transform is null, while from my pov if hit.transform is null, then the hit.transform.gameObject check and tag check musnt be executed.

Everything works after changing this line to the following code:

if ((hit) & (hit.collider) & (hit.transform)) {
                    if ((hit.transform.gameObject)&(hit.transform.gameObject.tag=="Toy")) {
// do something
}
}

Is it normal? So does unity always evaluate all items in the & if clause, even if it doesnt make sense? Or I am missing something (probably I do :))

Thank you for your help,

Leszek

I’m going to make some assumptions on this (which always goes well!). This is using

OnCollisionEnter(Collision hit)
{
     // Your code in here
}

and you want to check if the other items tag == Toy. All you need is this…

OnCollisionEnter(Collision hit)
    {
         if(hit.tag == "Toy")
             {
                   // do your actions in here
             }
    }