im working on a combat script and when it goes to deal damage to the enemy it says “Object reference not set to an instance of an object” on line 31 of “PlayerCombat”
I have a component in the enemy object named “Enemy” which is a script.
PlayerCombat
using UnityEngine;
public class PlayerCombat : MonoBehaviour
{
private float timeBtwAttack;
public float startTimeBtwAttack;
public Transform attackPos;
public LayerMask whatIsEnemies;
public Animator playerAnim;
public Vector3 attackRange = new Vector3(0.0f, 0.0f, 0.0f);
public int damage;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if(timeBtwAttack <= 0)
{
if (Input.GetKey(KeyCode.Z))
{
playerAnim.SetTrigger("Attack");
Collider2D[] enemiesToDamage = Physics2D.OverlapBoxAll(attackPos.position, attackRange, whatIsEnemies);
for (int i = 0; i < enemiesToDamage.Length; i++)
{
enemiesToDamage[i].GetComponent<Enemy>().TakeDamage(damage);
}
}
timeBtwAttack = startTimeBtwAttack;
} else
{
timeBtwAttack -= Time.deltaTime;
}
}
void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireCube(attackPos.position, attackRange);
}
}
“Enemy” script
using UnityEngine;
public class Enemy : MonoBehaviour
{
public float health;
private Animator anim;
public GameObject hitEffect;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
if (health <= 0)
{
Destroy(gameObject);
}
}
public void TakeDamage(int damage)
{
Instantiate(hitEffect, transform.position, Quaternion.identity);
health -= damage;
Debug.Log("Enemy health: " + health);
}
}