Confused on what != null does

Why do we need the if statement in the Playhiteffect method? Couldn’t you just have the code that’s in the brackets.

void PlayHitEffect()
    {
        if (hitEffect != null)
        {
            ParticleSystem instance = Instantiate(hitEffect, transform.position, Quaternion.identity);
            Destroy(instance.gameObject, instance.main.duration + instance.main.startLifetime.constantMax);
        }
    }

Hi BenCour,

!= means “not equal”, thus hitEffect != null translates to "hitEffect is not null".

Yes, we could execute the code without the if-statement but if hitEffect is null, Instantiate(hitEffect, ...) would throw a NullReferenceException error. To prevent this from happening, we check for null.

Did this clear it up for you? :slight_smile:


See also:

Yes that clears it up thanks

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