- Home /
NullReferenceExeption on OnCharacterControllerHit
In my game, when a character jumps on a certain object, it is supposed to do something. As the code follows, when the character jumps on a object, the character takes the parent's name. Depending on the name, it will do something, but at the if.. then.. statement in the code, there is a NullReferenceExeption when the character jumps on anything. Heres the code:
function OnControllerColliderHit (hit : ControllerColliderHit) {
var name = hit.gameObject.transform.parent.name;
if (name == "Thing") {
Debug.Log("Yay!");
}
}
What is the NullReference Exception you are getting . can you post the full exception(error) message?
Answer by robertbu · Feb 17, 2013 at 07:42 PM
Your code will will generate a null reference exception if the game object you collided with does not have a parent. If parent == null then your "parent.name" will generate the exception.
I tried your idea with this code:
function OnControllerColliderHit (hit : ControllerColliderHit) {
var name : String;
if (hit.collider.transform.childCount == 0) {
name = hit.gameObject.transform.name;
} else if (hit.collider.transform.childCount > 0) {
name = hit.gameObject.transform.parent.name;
}
if (name == "Thing") {
Debug.Log("Yay!");
}
}
Still, a NullReferenceException.
The NullReferenceException should provide you will a line number. Could you post the full output of the error in the Error log?
Sure. It says: NullReferenceException CharacterDini.OnControllerColliderHit (UnityEngine.ControllerColliderHit hit) (at Assets/Zardainian Quest/Assets/Characters/$$anonymous$$ain Characters/Dini/CharacterDini.js:217) UnityEngine.CharacterController:$$anonymous$$ove(Vector3) CharacterDini:FixedUpdate() (at Assets/Zardainian Quest/Assets/Characters/$$anonymous$$ain Characters/Dini/CharacterDini.js:194)
Just letting you guys know, the line #'s don't coordinate with the code i have posted before, so yeah.
I've never used childCount, but according to the reference, transform.childCount is the number of children of a specific transform. It does not indicate that the transform has a parent. I'd change your check to
if (hit.collider.transform.parent == null)
Your answer
Follow this Question
Related Questions
Combining if Statements 1 Answer
Single line if statement with many conditions or several single-conditioned if statements 1 Answer
Why does if(levelToLoad ==null) not work? 2 Answers
C# Declaring Variables Within If Statements 2 Answers
If/else statements working one way, and not the other 0 Answers