Search Unity

[Solved]NullReferenceException: Object reference not set to an instance of an object

Discussion in 'Scripting' started by PhiliipYoung, Dec 27, 2014.

  1. PhiliipYoung

    PhiliipYoung

    Joined:
    Dec 27, 2014
    Posts:
    2
    Hi guys, I am a new to the unity. I met a problem when I was dealing with Phrase 6 "Player Health" in a tutorial pack named nightmare in the asset store.

    When the Zombunny hit the player, the health of the player doesn't decrease.

    The error said
    NullReferenceException: Object reference not set to an instance of an object
    CompleteProject.EnemyAttack.Update () (at Assets/_CompletedAssets/Scripts/Enemy/EnemyAttack.cs:58)

    I have checked everything but could not find out why. I already attached the PlayerHealth script to the player.
    20141226214123.jpg

    Related links:
    http://forum.unity3d.com/threads/nu...e-not-set-to-an-instance-of-an-object.274788/

    http://forum.unity3d.com/threads/nu...an-instance-of-an-object.273747/#post-1892620


    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class EnemyAttack : MonoBehaviour
    5. {
    6.     public float timeBetweenAttacks = 0.5f;
    7.     public int attackDamage = 10;
    8.  
    9.  
    10.     Animator anim;
    11.     GameObject player;
    12.     PlayerHealth playerHealth;
    13.     //EnemyHealth enemyHealth;
    14.     bool playerInRange;
    15.     float timer;
    16.  
    17.  
    18.     void Awake ()
    19.     {
    20.         player = GameObject.FindGameObjectWithTag ("Player");
    21.         playerHealth = player.GetComponent <PlayerHealth> ();
    22.  
    23.         //enemyHealth = GetComponent<EnemyHealth>();
    24.         anim = GetComponent <Animator> ();
    25.     }
    26.  
    27.  
    28.     void OnTriggerEnter (Collider other)
    29.     {
    30.         if(other.gameObject == player)
    31.         {
    32.             playerInRange = true;
    33.         }
    34.     }
    35.  
    36.  
    37.     void OnTriggerExit (Collider other)
    38.     {
    39.         if(other.gameObject == player)
    40.         {
    41.             playerInRange = false;
    42.         }
    43.     }
    44.  
    45.  
    46.     void Update ()
    47.     {
    48.         timer += Time.deltaTime;
    49.  
    50.         if(timer >= timeBetweenAttacks && playerInRange/* && enemyHealth.currentHealth > 0*/)
    51.         {
    52.             Attack ();
    53.         }
    54.  
    55.         if(playerHealth.currentHealth <= 0)
    56.         {
    57.             anim.SetTrigger ("PlayerDead");
    58.         }
    59.     }
    60.  
    61.  
    62.     void Attack ()
    63.     {
    64.         timer = 0f;
    65.         if(playerHealth.currentHealth > 0)
    66.         {
    67.             playerHealth.TakeDamage (attackDamage);
    68.         }
    69.     }
    70. }
    71.  
     
  2. toreau

    toreau

    Joined:
    Feb 8, 2014
    Posts:
    204
    It doesn't seem like the "anim" variable is set. Can you throw in a Debug.Log() to confirm this?
     
  3. PhiliipYoung

    PhiliipYoung

    Joined:
    Dec 27, 2014
    Posts:
    2
    I have solved the problem. By commenting out the EnemyHealth and its related parameters in MonoDevelop.

    Before that I always directly edit the .cs files with the SublimeText editor instead of MonoDevelop.
    And the parameters have already been commented out in the cs files. But they are not commented out in the EnemyAttack.cs.meta file.

    I think Unity calls the EnemyAttack.cs.meta instead of EnemyAttack.cs.

    Anyway, thanks a lot. Maybe it is better to keep using the MonoDevelop to edit the .cs files.
     
  4. ymasdev

    ymasdev

    Joined:
    Sep 5, 2018
    Posts:
    2
    i am new to C# and i am having a similar issue. i commented out my anim line and it still does not work. Please look at the code and help me i have spent hours trying to find this problem. here is my code....

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.AI;

    public class ClickToMove : MonoBehaviour {
    [Header("Stats")]
    public float attackDistance;
    public float attackRate;
    private float nextAttack;

    private NavMeshAgent navMeshAgent;
    private Animator anim;

    private Transform targetedEnemy;
    private bool enemyClicked;
    private bool walking;
    void Awake ()
    {
    anim = GetComponent<Animator>();
    navMeshAgent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update ()
    {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;

    if (Input.GetButtonDown("Fire2"))
    {
    if (Physics.Raycast(ray, out hit, 1000))
    {
    if (hit.collider.tag == "Enemy")
    {
    targetedEnemy = hit.transform;
    enemyClicked = true;
    }
    else
    {
    walking = true;
    enemyClicked = false;
    navMeshAgent.isStopped = false;
    navMeshAgent.destination = hit.point;
    }
    }
    }
    if (enemyClicked)
    {
    MoveAndAttack();
    }

    if (navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
    {
    walking = false;
    }
    else
    {
    walking = true;
    }

    //anim.SetBool("isWalking", walking);
    }

    void MoveAndAttack()
    {
    if(targetedEnemy == null)
    {
    return;
    }

    navMeshAgent.destination = targetedEnemy.position;

    if(navMeshAgent.remainingDistance > attackDistance)
    {
    navMeshAgent.isStopped = false;
    walking = true;
    }
    else
    {
    transform.LookAt(targetedEnemy);
    Vector3 dirToAttack = targetedEnemy.transform.position - transform.position;

    if(Time.time > nextAttack)
    {
    nextAttack = Time.time + attackRate;
    }
    navMeshAgent.isStopped = true;
    walking = false;
    }
    }
    }
     
  5. ymasdev

    ymasdev

    Joined:
    Sep 5, 2018
    Posts:
    2
    the error message is this....
    NullReferenceException: Object reference not set to an instance of an object
    ClickToMove.NewMethod () (at Assets/Scripts/ClickToMove.cs:67)
    ClickToMove.Update () (at Assets/Scripts/ClickToMove.cs:27)

    on line 27 is the code...
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     
  6. juraijtanveer

    juraijtanveer

    Joined:
    Jan 21, 2019
    Posts:
    2
    the error message is this....
    NullReferenceException: Object reference not set to an instance of an object
    ClickToMove.NewMethod () (at Assets/Scripts/ClickToMove.cs:67)
    ClickToMove.Update () (at Assets/Scripts/ClickToMove.cs:27)
    the error message is this....


    using UnityEngine;

    using UnityEngine.UI;

    using UnityEngine.SceneManagement;

    using System.Collections;

    using admob;

    public class GameManager : MonoBehaviour {
    // Use this for initialization

    public GameObject pausepanel, Levelcomplete, Levelfailed, objectivepanel;

    public GameObject[] LevelObjects, objective;

    GameObject player, fppos;

    public static int nextStatus = 0;


    int getlevel = 0;


    void Awake () {
    nextStatus = 0;


    getlevel = PlayerPrefs.GetInt("Level");


    foreach (GameObject item in objective) {

    item.SetActive (true );
    }

    objective [getlevel - 1].SetActive (true);

    objectivepanel.SetActive (true);

    for (int i = 0; i < LevelObjects.Length; i++) {

    LevelObjects .SetActive (false);

    }

    LevelObjects [getlevel - 1].SetActive (true);

    player = GameObject.Find ("FPS Main");

    fppos = GameObject.Find ("Level" + getlevel + "FPSPos");

    player.transform.position = fppos.transform.position;

    player.transform.rotation = fppos.transform.rotation;


    }


    // Update is called once per frame

    void Update ()
    {




    }


    public void pause()

    {

    StartCoroutine (DelayPause ());

    pausepanel.SetActive (true);

    }

    IEnumerator DelayPause(){

    yield return new WaitForSeconds (1f);

    Time.timeScale = 0.0f;

    }

    public void resume()

    {

    Time.timeScale = 1f;
    Admob.Instance ().removeBanner ("GunSelect");
    pausepanel.SetActive (false);

    }


    public void restart()

    {

    Admob.Instance ().removeBanner ("GunSelect");

    GameManager.nextStatus = 0;

    Time.timeScale = 1f;

    SceneManager.LoadScene ("GamePlay");

    }

    public void Home()
    {

    Admob.Instance ().removeBanner ("GunSelect");

    GameManager.nextStatus = 0;

    Time.timeScale = 1f;

    SceneManager.LoadScene ("Main_Menue");

    }


    public void next(){

    Admob.Instance ().removeBanner ("GunSelect");

    nextStatus = PlayerPrefs.GetInt("Level")+1;

    PlayerPrefs.SetInt ("LvlActive", nextStatus);

    SceneManager.LoadScene ("LevelSelection");

    }




    public void closeObjective(){

    TopManagerGame.level15PanelCloseStatus = 1;

    TopManagerGame.level20PanelCloseStatus = 1;

    TopManagerGame.timestatus = 1;

    objectivepanel.SetActive (false);

    }
    }