0

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
    }
}```
derHugo
  • 83,094
  • 9
  • 75
  • 115
Tharasian
  • 1
  • 1
  • Between the `<>` of a generic method (like GetComponent) you should have a Type, not an instance. What is the type of enemy1? – Hans Kesting Sep 24 '22 at 09:58
  • @HansKesting if `enemy1` wasn't a type then the code wouldn't even compile ... provided code here can not be the actually used code ... – derHugo Oct 18 '22 at 14:57

0 Answers0