Does guarding against `null` really make sense here?

In the video at about 3:00-3:10 there is this line

Image image = child?.GetComponent<Image>();

Now, we should be pretty certain that we have setup the staminaContainer to contain a number of images that we can grab and not much else, but having a check can’t hurt either (and one might want to add some decoration between the stamina globes, although one would likely run into an issue with that decoration being images as well, so one would need some other way to differentiate between the stamina globes and the decoration).

But what happens in case we get a child object that is actually not an image we can grab the sprite from?

if(...)
  {  image.sprite = fullStaminaImage; }
else
  {  image.sprite = emptyStaminaImage; }

Either of these assignments would fail if image became null from that GetComponent<>() call…

So one would have to also check for this, as well…

That’s correct.

Often, we leave out the needed null checks, often depending on a correct setup.

That’s what tends to get relied on in coding for the courses. We try to keep our lectures as compact as possible, aiming for 10-15 minutes (we often go over). In Stephen’s case, everything is set up correctly in the inspector, so the code should work flawlessly.

I have a hard and fast rule, which I always recommend students follow as they follow the courses (this applies to everything, our courses, Penny’s Holistic courses, or anybody’s courses…

If it can be null, it must be null checked

Now this shouldn't add as many null checks as one might think. Once an item IS null checked within a method, its' safe to assume that it will stay not null through the method (unless it's a Coroutine, in which case, any pointer from outside the coroutine must be null checked).

For example:

Image image = child?.GetComponent<Image>();
if(image==null) return; //blocking null check

Once this null check has passed, then the if/else cases later can logically be presumed to be valid.

My personal preference for the Image image = child?.GetComponent() is to use the TryGetComponent instead

if(child!=null && child.TryGetComponent(out Image image)
{
    //put the rest of the code here  Within this block, image is
    //GUARANTEED to be a valid Image component
}

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

Privacy & Terms