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();
}