Object reference not set to an instance of an object C# Unity

Viewed 10

Below is my code for melee attacks. I am not sure why but at line 44 enemy1.GetComponent<enemy1>().TakeDamage(damage); it tells me an object reference is required for the non-static field, method, or property 'Component.GetComponent()' Where enemy1 is the script for the enemy to get damaged.

EDIT: So i figured the mistake in the code, rather than using the script first, it should be the unit in the for loop. HOWEVER, I am getting object reference not set to an instance of an object now in the same line

using System.Collections.Generic;
using UnityEngine;

public class Melee : MonoBehaviour
{
    private float timeBtwAttack;
    public float startTimeBtwAttack;
    public Transform attackPos;
    public float attackRange;
    public LayerMask enemies;
    public int damage;
    public Animator anim;

    private void Update()
    {
        if(timeBtwAttack <= 0)
        {
            if (Input.GetKey(KeyCode.Alpha1))
            {
                attack();
            }
            timeBtwAttack = startTimeBtwAttack;
        }
        else
        {
            timeBtwAttack -= Time.deltaTime;
        }
    }
    private void OnDrawGizmosSelected()
    {if (attackPos == null) return;
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(attackPos.position, attackRange);
    }
    void attack()
    {
        //play an attack
        anim.SetTrigger("attack");
        //detect enemies
        Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, enemies);
        foreach(Collider2D enemy in enemiesToDamage)
        {
            Debug.Log("We hit " + enemy.name);
           enemy1.GetComponent<enemy1>().TakeDamage(damage);
        }
        //damage enemies
    }
}```
0 Answers
Related