Using a variable before it is set

Hello all.

I am a bit puzzled by this implementation.

Many students are having this null reference error in their codes and maybe it is because the teacher set the bool ternary to use a reference that is not yet set.

bool isInRange = Vector3.Distance(target.position, transform.position) < weaponRange;
      if (target && !isInRange)
      {
        moveScript.MoveTo(target.position);
      }
      else
      {

        moveScript.Stop();
      }

Wouldn’t be better if the bool was set after the value for target was caught and then a check made to see if the player was within range? This way the null assertion errors are gone and the player can move freely until there is a click on the enemy.

if (target)
      {
        moveScript.MoveTo(target.position);

        bool isWithinRange = Vector3.Distance(target.position, transform.position) <= weaponRange;

        if (isWithinRange) moveScript.Stop();
      }
2 Likes

I am just doing this lesson, as well. I am throwing the null reference as well, but it interesting that the instructor is also throwing the same null reference but his character is still moving. Mine just will not move at all.

1 Like

Try holding the mouse button. For some reason the target reference always returns null and the action is stopped. The instructor actually fixes this in a later lesson by passing

if (tager == null) return

before the distance check and also by turning the check into a void function itself, this time being called in a if statement after the null check.
The solution is quite smart and makes the methods as dry as possible.

You’re quite right! This is something we fix in a couple of lectures, but this is an excellent solution.

Privacy & Terms