- Home /
Can't find the null reference
I have been coding a combat system for my platformer, and I am now getting NullReferenceException: Object reference not set to an instance of an object
But I just cant find where, Here is the code segment where the error is. health is declared at the start of the function and hit is a raycast2D
if(hit != null){
health = hit.transform.gameObject.GetComponent<Health>(); //Debugger says error is on this line
if(health != null){
succesful = true;
health.hit (secondaryPower);
}else{
succesful = false;
}
I am probably just being stupid again, thanks for any help you may give.
Have you made sure that the object that the raycast is hitting has the script you looking for?
If you can post some more code i easier to see exactly what you have done.
If it cant get the component health will be equal to null right? thats why I have the if statement "if(health != null)"
Answer by robertbu · Jul 21, 2014 at 06:49 PM
Rewrite your first line to:
if(hit != null && hit.transform != null){
I've received conflicting information about RaycastHit2D. It is a struct (so it cannot be a null referene), but I've read somewhere that the equals is overridden to make null checks work, but there have been a number of questions come across the list where what I outline (checking hit.collider or hit.transform) is necessary to solve the problem. In fact you could probably not even check if the 'hit' is null and just check the transform or the collider.