Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by nathangjdavison, Dec 1, 2023.

  1. nathangjdavison

    nathangjdavison

    Joined:
    Mar 28, 2023
    Posts:
    1
    In my code an issue popped up where it said
    NullReferenceException: Object reference not set to an instance of an object
    PlayerCombat.Attack () (at Assets/PlayerCombat.cs:42)
    PlayerCombat.Update () (at Assets/PlayerCombat.cs:28)

    I was wondering if there were any ways to fix this error. Any help would be much appreciated.

    Code (CSharp):
    1.  
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5. public class PlayerCombat : MonoBehaviour
    6. {
    7.     public Animator animator;
    8.     public float timeTakenToAttack = 0.25f;
    9.     public float attackSpeed = 2f;
    10.     float nextAttack = 0f;
    11.     public Transform attackPoint;
    12.     public LayerMask enemyLayers;
    13.    
    14.     public float attackRange = 0.5f;
    15.     public int attackDamage = 10;
    16.     void Update()
    17.     {
    18.         if(Time.time >= nextAttack)
    19.         {
    20.             if (Input.GetKeyDown(KeyCode.Space))
    21.             {
    22.                 Attack();
    23.                 nextAttack = Time.time + 1f / attackSpeed;
    24.             }
    25.         }
    26.     }
    27.     void Attack()
    28.     {
    29.         animator.SetTrigger("Attack");
    30.         Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
    31.         foreach(Collider2D enemy in hitEnemies)
    32.         {
    33.             enemy.GetComponent<Zombie>().TakeDamage(attackDamage);
    34.         }
    35.     }
    36.     void OnDrawGizmosSelected()
    37.     {
    38.         if (attackPoint == null)
    39.             return;
    40.        
    41.         Gizmos.DrawWireSphere(attackPoint.position, attackRange);
    42.     }
    43. }
    44.  
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,105
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,278