Arrow does not go to the target

When I launch the projectile the console says null reference error in the update method like saying that there is no target.
I followed all the steps and printed the target name through all the calls and it goes well until the projectile has to go to the target, it stays in the place where is instanciated.

Paste in your Projectile.cs script as well as just the Hit() method in Fighter.cs and we’ll take a look.

public class Projectile : MonoBehaviour
    {
        [SerializeField] private float speed = 1f;
        [SerializeField] private bool isHoming = true;

        private Health target = null;
        private float damage = 0;

        private void Start()
        {
            transform.LookAt(GetAimLocation());
        }

        private void Update()
        {
            if (target == null) { return; }

            if (isHoming && !target.IsDead())
            {
                transform.LookAt(GetAimLocation());
            }
            transform.Translate(Vector3.forward * speed * Time.deltaTime);
        }

        public void SetTarget(Health target, float damage)
        {
            this.target = target;
            this.damage = damage;
        }

        private Vector3 GetAimLocation()
        {
            CapsuleCollider targetCapsule = target.GetComponent<CapsuleCollider>();
            
            if (targetCapsule == null) { return target.transform.position; }
            
            return target.transform.position + Vector3.up * targetCapsule.height / 2;
        }

        private void OnTriggerEnter(Collider other)
        {
            if (other.GetComponent<Health>() != target) { return; }
            if (target.IsDead()) { return; }

            target.TakeDamage(damage);

            Destroy(gameObject);
        }
    }

void Hit()
        {
            if (_target == null) { return; }

            if ( currentWeapon.HasProjectile())
            {
                currentWeapon.LaunchProjectile(righHandTransform, leftHandTransform, _target);
            }
            else
            {
                _target.TakeDamage(currentWeapon.GetDamage());
            }
        }

It looks like your Weapon.LaunchProjectile() method isn’t taking in the target, damage and damage dealer as discussd in Shoot Projectiles.
Here’s the Course Repo’s version of Weapon.LaunchProjectiles()

        public void LaunchProjectile(Transform rightHand, Transform leftHand, Health target)
        {
            Projectile projectileInstance = Instantiate(projectile, GetTransform(rightHand, leftHand).position, Quaternion.identity);
            projectileInstance.SetTarget(target);
        }

Found it thanks to the Repo’s Version.
I was setting the target and damage to “projectile” instead of “projectileInstance”.

Thank you Brian

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms