Search Unity

Object reference not set to an instance of an object error.

Discussion in '2D' started by zawesome1234, Jun 21, 2019.

  1. zawesome1234

    zawesome1234

    Joined:
    Jun 21, 2019
    Posts:
    2
    I keep getting this error "NullReferenceExeception: Object reference not set to an instance of an object" I've looked at several threads in this forum and others and none of the solutions have worked for me so here is my code I hope there's you all know what's going wrong, thx.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class healthBar : MonoBehaviour
    6. {
    7.     private playerController healthRemove;
    8.     private Animator anim;
    9.  
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         anim = GetComponent<Animator>();
    15.         healthRemove = GetComponent<playerController>();
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         anim.SetFloat("Health", healthRemove.health);
    22.     }
    23. }
    24.  
     
    Last edited: Jun 21, 2019
  2. tashfiq103

    tashfiq103

    Joined:
    Mar 4, 2016
    Posts:
    15
    GoodPractice : A class name should be start off with the capital letter, so instead of "playerController", it should be "PlayerController".

    Troubleshoot ;
    (1) Make sure your following gameObject has attached with the following component which you were trying to get reference in the "Start()" function. The code should have worked fine.
     
  3. zawesome1234

    zawesome1234

    Joined:
    Jun 21, 2019
    Posts:
    2
    Like I said earlier I have followed many community instructions and have made sure all of the references are correct. I'm not sure what is causing it but I decided to write an entirely new script of the same type and still got that error even without the fluff. Is there anything else that could be causing it? Thanks.
     
  4. tashfiq103

    tashfiq103

    Joined:
    Mar 4, 2016
    Posts:
    15
    "anim.SetFloat(value)" could be an issue as you are trying to constantly calling it from the update function.

    Is there anyway the following call can be asynchronous? Like when there is any chance in the "health" status, you will call the "anim.SetFloat(currentHealth)" ?

    I think this should solve the problem.