Hello! I am in a Game Design class that makes us have to make prototypes. I am trying to make a combo system and am making a basic combat system first. I am trying to make it to where the enemy is registered as being hit and that their health goes down. However I keep getting the issue:
NullReferenceException: Object reference not set to an instance of an object. Here is my code for the player when it comes to the attacks:
// Detect enemy in range of attack
Collider2D[ ] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange);//enemyLayers);
Debug.Log(hitEnemies.Length);
// Damage them
foreach(Collider2D enemy in hitEnemies)
{
Debug.Log(enemy);
Enemy EnemyReference = enemy.GetComponent();
EnemyReference.TakeDamage(attackDamage);
}
void OnDrawGizmosSelected()
{
if (attackPoint == null)
Gizmos.DrawWireSphere(attackPoint.position, attackRange);
}
And here’s the enemy’s script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
public void TakeDamage(int damage)
{
currentHealth -= damage;
Debug.Log(“Enemy hit!”);
// Play hurt animation
if(currentHealth <= 0)
{
Die();
}
}
void Die()
{
Debug.Log(“Enemy has died!”);
// Die animation
Make sure to read some of the top stickies of the forum, one of them is how to solve a NullReferenceException , and another is how to properly format code in your thread . Another thing to note is that almost all errors also provide a line number along with the error, so if you want people to actually be able to help you, you should include the entire error.
First off, you should use code tags when you post code. That will give the code line numbers and color code it. It’s much easier for us to read and understand that way.
Well you never even check if the colliders you hit have enemy components, you just try to get it. If your game has a wall, it probably has a collider, and I’m guessing it wouldn’t have an enemy component, so why would you expect everything in your OverlapCircle to have an enemy component?
You’re using Physics2D.OverlapCircleAll without a layer mask. I see you’ve commented out a variable called enemyLayers. If you want it to only find colliders in the enemy layer, determine which layer number that is and stick it in the variables for OverlapCircleAll. Otherwise, as RadRedPanda said, you’re picking up every collider within that circle and some of them probably aren’t enemies and don’t have the Enemy script.