cloneChild != null

Hey, I was just wondering on the UnitRagdoll.cs when we are iterating through the child components of the root bone we check whether the cloneChild is null. Why do we need to do this? What scenario would occur where you were the cloneChild is null?

The ragdolls and the units are different prefabs. There is nothing keeping them ‘in sync’. If a transform exists in the unit that is not in the ragdoll, the clone.Find() will return a null. Things like weapons. You’re not going to put the sword - for example - in the ragdoll because it’s not going to be visible when the ragdoll is active. Unless your units walk around with the sword when they’re idle, but we’re not. So, the unit may have the sword transform in hand (albeit disabled) but the ragdoll does not have a sword. So, the cloneChild for the sword would be null

To add to that, let me add the following maxim:

If it can be null, it should be null checked.

While we don’t always emphasize this in all of our courses, we always have to be vigilant about references and the possibility of their being null. This includes any time you GetComponent<T>, FindObjectOfType<T>, GameObject.FindWithTag(), SerializedField references, and anything passed through method parameters.

There are instances where you can assume that a reference value cannot be null. A great example is if you have something like a [RequireComponent] tag on a class, then it’s safe to assume that a GetComponent in that class for the Required class should not be null. Another is calling a private method that you know the reference was properly null checked before calling the method… for example:

public void DamageHealth(Health health, float amount)
          //Within this if, health is guaranteed not to be null
          if(GetHealthRemainingPercent(health)<.10f) Debug.Log("Warrior is about to die!");
private float GetHealthRemainingPercent(Health health)
     //In this abstract scenario, this method is only called by DamageHealth, which has already null checked Health
     return health.GetHitPointsRemaining()/health.GetMaxHitPoints();

This is a silly example, but it’s one of the rare scenarios in which you could safely skip null checking.

1 Like

Privacy & Terms