I think this is cleaner code here

just wanted to show how I coded this lecture during the challenge, I think it’s a bit cleaner than @sampattuzzi 's solution. Someone tell me if I’m crazy…as I am a novice…

using RPG.Movement;
using UnityEngine;

namespace RPG.Combat
{
    public class Fighter : MonoBehaviour
    {
        // SHIPPING DATA //



        // CHANGING DATA //
        Transform target;
        Mover moverScript;
        [SerializeField] float weaponRange = 2f;



        // * CODE * //

        void Start()
        {
            moverScript = GetComponent<Mover>();
        }

        void Update()
        {
            if (target != null)
            {
                MoveToAttack();
            }
        }

        private void MoveToAttack()
        {
            moverScript.MoveToTarget(target.position);
            if (Vector3.Distance(target.position, transform.position) <= weaponRange)
            {
                moverScript.StopMovement();
            }
        }

        public void Attack(CombatTarget combatTarget)
        {
            target = combatTarget.transform;
            print("take that " + combatTarget + " you flat faced heathen!");
        }

        public void StopAttacking()
        {
            target = null;
        }

    }
}

While I’m not qualified to judge anybody sanity, the code itself looks fine. It is generally better to cache references to things like mover than to call them every update as Sam has done here.

Will this part of the code cause some weird behavior?
You asked the mover to move and then to stop.

I don’t know how does Unity engine handle function calls. I am going to assume a function call can span more than 1 frame.
Imagine that MoveToAttack spans over three frames.

  • At frame 0 the Mover is asked to move towards the target.
  • And at frame 2 the Mover is asked to stop.

It may cause the Player to jitter during frame 1.
I am not saying it will happen given how short the function is. But hypothetically it can happen with very specific scenario. And you will have a stubborn bug.

Actually, unless a function is a coroutine, the entire function will run in the same frame. This is one reason we have to pay special attention to how much code we actually run in a function in the first place.

So in frame X:
MoveToTarget() is called,
The distance is checked against the weaponrange
the mover is told to stop

Privacy & Terms