Search Unity

How to Make Enemy Attack When In Range of The Player?

Discussion in 'General Discussion' started by Asimraza144, Nov 10, 2021.

  1. Asimraza144

    Asimraza144

    Joined:
    Nov 10, 2021
    Posts:
    1
    So my game is a 2D top down movement game and my script does make my enemy attack but it constantly loops the attack animation because I obviously don't know what EXACTLY to put code wise to make the enemy attack when in range of the player to do damage instead of letting him constantly loop. Also i seem to be getting an error when i get close to my enemy as of right now it says

    NullReferenceException: Object reference not set to an instance of an object EnemyCombat.Attack () (at Assets/EnemyCombat.cs:36) EnemyCombat.Update () (at Assets/EnemyCombat.cs:25) Link

    Also, Here is the EnemyCombat script
    Code (CSharp):
    1.  
    2.    enemy attausing System.Collections;
    3.    using System.Collections.Generic;
    4.    using UnityEngine;
    5.  
    6.    public class EnemyCombat : MonoBehaviour
    7.    {
    8.        public Animator animator;
    9.  
    10.        public Transform AttackPoint;
    11.  
    12.        public float attackRange = 0.5f;
    13.  
    14.        public LayerMask enemyLayers;
    15.  
    16.        public int attackDamage = 5;
    17.  
    18.        public float attackRate = 2f;
    19.        float nextAttackTime = 0f;
    20.  
    21.        // Update is called once per frame
    22.        void Update()
    23.        {
    24.            if (Time.time >= nextAttackTime)
    25.            {
    26.                Attack();
    27.                nextAttackTime = Time.time + 1f / attackRate;
    28.            }
    29.        }
    30.  
    31.        void Attack()
    32.        {
    33.            animator.SetTrigger("Attack");
    34.            Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackPoint.position, attackRange, enemyLayers);
    35.            foreach (Collider2D enemy in hitEnemies)
    36.            {
    37.                enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
    38.            }
    39.        }
    40.  
    41.        void OnDrawGizmosSelected()
    42.        {
    43.            if (AttackPoint == null)
    44.                return;
    45.  
    46.            Gizmos.DrawWireSphere(AttackPoint.position, attackRange);
    47.        }
    48.    }
     
  2. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,569
    Code (csharp):
    1.  
    2. enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
    3.  
    What do you think is going to happen when some of the objects you got have no "Enemy" components on them?