- Home /
NullReferenceException
plz help me with this error! NullReferenceException: Object reference not set to an instance of an object HealthScript.OnControllerColliderHit (UnityEngine.ControllerColliderHit other) (at Assets/HealthScript.cs:51)
using UnityEngine;
using System.Collections;
public class HealthScript : MonoBehaviour {
public float maxHealth = 500.0f ;
float health = 0.0f ;
public float regeneration = 10.0f ;
// Use this for initialization
void Start () {
health = maxHealth ;
}
// Update is called once per frame
void Update () {
if(health < maxHealth){
health += regeneration * Time.deltaTime ;
}
if(health > maxHealth)
health = maxHealth ;
if(health == 0 || health < 0)
Application.LoadLevel("zerohealth");
}
void OnGUI(){
if(health < maxHealth){
Color tempColour = GUI.color ;
GUI.color = Color.blue;
GUI.Box (new Rect(620,60,100,30), "Health:"+health+"/"+maxHealth);
GUI.Label(new Rect((Screen.width / 2) - 70, (Screen.height / 2) - 20, 140, 40), "OUCH THAT HURTS");
GUI.color = tempColour ;
}
}
void OnControllerColliderHit(ControllerColliderHit other){
if(other.gameObject.CompareTag("Health")){
HealthAttributes otherScript = other.gameObject.GetComponent();
ApplyDamage(otherScript.damageToInflict) ;
}
}
void ApplyDamage(float damage){
health -= damage ;
}
}
and this is HealthAttributes script:
using UnityEngine;
using System.Collections;
public class HealthAttributes : MonoBehaviour {
public float damageToInflict = 1.0f ;
}
Answer by Graham-Dunnett · May 15, 2013 at 09:47 PM
NullReferenceException: Object reference not set to an instance of an object
HealthScript.OnControllerColliderHit (UnityEngine.ControllerColliderHit other)
(at Assets/HealthScript.cs:51)
There are three critical pieces of information here:
`NullReferenceException` - this means that you are using a variable that has not been assigned a value, and you are using it without first checking if it's not null.
`HealthScript.OnControllerColliderHit` - you have a script called
HealthScript
and it contains a function calledOnControllerColliderHit
that has the problem in it somewhere.HealthScript.cs:
`51` - line 51 of the script has the problem.
Now, because your question does not have the code correctly formatted I cannot easily tell you what line 51 is. You can find out, and fix it. You are calling GetComponent()
without telling the function what component you want, so that's probably your mistake
Answer by crogersKixeye · May 15, 2013 at 09:39 PM
Basically you have to check every variable to make sure it isnt null before you try to read it.
if (a != null) doSomething().....
i dont understand where your error is happening, but in general make sure you have given it a value, and that it hasnt gone out of scope.