Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

object reference not set to an instance of an object (HELP)

Discussion in 'Scripting' started by j7stin, Feb 6, 2020.

  1. j7stin

    j7stin

    Joined:
    Jan 7, 2020
    Posts:
    22
    Good day everyone,

    I'm making a game where you literally run away from a few dudes who are trying to kill you and I would like to make a system in which when you are 10 units on the Z axis away from the enemy, you will take damage.

    This is my PlayerHealth class:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerHealth : MonoBehaviour
    6. {
    7.     public float maxHealth;
    8.     public float currentHealth;
    9.    
    10. }
    11.  
    This is my (I say my but I honestly mean Brackey's) EnemyController script:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.AI;
    3. using System.Collections;
    4.  
    5. /* Makes enemies follow and attack the player */
    6.  
    7.  
    8. public class EnemyController : MonoBehaviour
    9. {
    10.  
    11.     public float lookRadius = 10f;
    12.  
    13.     Transform target;
    14.     NavMeshAgent agent;
    15.     PlayerHealth playerHealth;
    16.  
    17.     void Start()
    18.     {
    19.         target = PlayerManager.instance.player.transform;
    20.         agent = GetComponent<NavMeshAgent>();
    21.     }
    22.  
    23.     void Update()
    24.     {
    25.         // Get the distance to the player
    26.         float distance = Vector3.Distance(target.position, transform.position);
    27.  
    28.         if (distance <= lookRadius)
    29.         {
    30.             // Move towards the player
    31.             agent.SetDestination(target.position);
    32.             if (distance <= 10f)
    33.             {
    34.                 // Attack
    35.                 playerHealth.currentHealth -= 1f;
    36.                 FaceTarget();
    37.             }
    38.         }
    39.     }
    40.  
    41.     // Point towards the player
    42.     void FaceTarget()
    43.     {
    44.         Vector3 direction = (target.position - transform.position).normalized;
    45.         Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
    46.         transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    47.     }
    48.  
    49.     void OnDrawGizmosSelected()
    50.     {
    51.         Gizmos.color = Color.red;
    52.         Gizmos.DrawWireSphere(transform.position, lookRadius);
    53.     }
    54.  
    55. }
    When I play the game and I am within range, I get the error 'NullReferenceException: Object reference not set to an instance of an object EnemyController.Update () (at Assets/Scripts/EnemyController.cs:35).

    Could someone please help?

    Much appreciated :)
     
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,590
    A NullReferenceException tells you that you are accessing a something in a reference which is null, meaning it was not yet assigned, or does not exist anymore. In your case, the error tells you it's at EnemyController.cs:35, meaning line 35. In line 35 you wrote playerHealth.currentHealth -= 1;
    The problem here is that you never assigned the playerHealth reference to anything (no PlayerHealth object exists there), thus you effectively write null.currentHealth -= 1, which throws the exception. To fix that you need to create the object you want to use. It may be enough to write playerHealth = new PlayerHealth() in the Start() method, but i assume you want it to reference the actual health of your player, which you probably already created somewhere else. In that case you should reference that specific PlayerHealth object.

    On that note, if you do not use any of the Monobehaviour methods (Start, Update, ..) a class does not need to be derived from Monobehavior. So for PlayerHealth this is not necessary.

    Hope this helps :)
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    Adding that to Start wouldn't work either as each enemy would then have a different PlayerHealth value. Plus, new doesn't work if the class does inherit from Monobehaviour
     
    Yoreki likes this.
  4. j7stin

    j7stin

    Joined:
    Jan 7, 2020
    Posts:
    22
    Hey thanks a lot for the reply, I appreciate it, you helped me figure out what I was doing wrong. The only problem is that I still don't know how to fix it :(
    I tried the solutions you gave me but like @Brathnann said, it doesn't work.

    I searched for a fix but I literally found nothing.
     
    Last edited: Feb 6, 2020
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,151
    If you have a playerHealth component in the scene, either you need to drag and drop that object into the enemy playerHealth variable (if your enemies already exist) or you could just make it a singleton script since you'll only ever have one playerHealth. Otherwise, you'll want some sort of manager script that can assign that playerHealth instance to the enemies (if you are spawning in new enemies).
     
  6. Serinx

    Serinx

    Joined:
    Mar 31, 2014
    Posts:
    785
    You need to access your playerhealth somehow, Can we see the Player and PlayerManager script?

    My guess it that you'll be able to do this instead:

    PlayerManager.instance.player.health.currentHealth -= 1f;

    If all depends on whether your player script exposes the playerHealth component though.
     
  7. j7stin

    j7stin

    Joined:
    Jan 7, 2020
    Posts:
    22
    To be fair I don't really have a playermanager script, it's just this

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerManager : MonoBehaviour
    6. {
    7.  
    8.     #region Singleton
    9.  
    10.     public static PlayerManager instance;
    11.  
    12.     private void Awake()
    13.     {
    14.         instance = this;
    15.     }
    16.  
    17.     #endregion
    18.  
    19.     public GameObject player;
    20.  
    21. }
     
  8. j7stin

    j7stin

    Joined:
    Jan 7, 2020
    Posts:
    22
    Thank you! This worked :D
     
  9. Iamabeginnerdeveloper

    Iamabeginnerdeveloper

    Joined:
    Dec 5, 2020
    Posts:
    1
    Hmmmm guys i am also using brackeys code but i have and error i am trying to make the player die after falling or hitting an obstacle but it shows me
    NullReferenceException: Object reference not set to an instance of an object
    PlayerCollision.OnCollisionEnter (UnityEngine.Collision collision
    i have no idea what is wrong here is the code that has the error



    using UnityEngine;
    public class PlayerCollision : MonoBehaviour
    {

    public PlayerMovement movement;

    void OnCollisionEnter (Collision collision)
    {
    if (collision.gameObject.tag == "Obstacle")
    {
    movement.enabled = false;
    FindObjectOfType<GameManager>().Endgame();
    }
    }
    }