Else mover.Stop() question

While my code for this lecture is working properly, I’m a little confused as to why mover.Stop() isn’t constantly being called and stopping my character’s movement mid-stride when I don’t have a target. Am I misunderstanding this function?

Thanks!

        private void Update()
        {
            bool isInRange = Vector3.Distance(transform.position, target.position) <= weaponRange;
            if (target != null && !isInRange)
            {
                 mover.MoveTo(target.position);
            }
            else
            {
                mover.Stop();
            }
        }

Actually, I’m surprised you don’t have a null reference exception when you don’t have a target…

We use this fragement of code when we’re setting the target in the inspector, but once the target is set in the game by PlayerController, we should be null checking before calculating isInRange.

The first line of Update should read
if(target==null) return;
Then the rest of the code can complete (you can remove the target check in that isInRange check.

Privacy & Terms