- Home /
Why am I getting a null reference exception
I am trying to get the height of my mesh so that when he crouches I can change the size of the capsule collider. So I would like to know what is the difference between the capsule collider and the character controller. Are they the same thing or does the character controller just include a collider? And the big question is how to get the size of the mesh? I have looked online and used the some of the code from the documentation of unity javascript. Here is my code:
pragma strict
/ This script get the collider of the object it is attached to // and makes sure that the collider stays around the object appropriately
private var mCollider : CharacterController;
var m : Mesh;
private var cHeight : float;
private var cCenter : Vector3;
private var mBounds : Bounds;
function Start ()
{
mCollider = GetComponent(CharacterController);
m = GetComponent(MeshFilter).mesh; // <-- This is the problem
// mBounds = m.bounds; <-- Commented out
// cHeight = mCollider.height; <-- ' '
// cCenter = mCollider.center; <-- ' '
}
function Update ()
{
//cCenter = mBounds.center; <-- ' '
}
I just for right now what to be able to set the collider height to the height of my mesh. This way I can scale down the collider with the height of my mesh. I don't want to scale the collider down by some constant that happens to be the height of my mesh. For example I probably could just half the height of the collider and be ok but I'd rather not do that. So why am I getting a null reference exception? How do I say that I am refering to the mesh that the script is attached to?
Answer by liszto · Nov 20, 2012 at 09:12 AM
You get null reference exception because you don't verify before do :
m = GetComponent(MeshFilter).mesh;
That thing really exist so if you're object don't have it you try to fill your var "m" with a null value cause your component doesn't exist on your GameObject.
You must ALWAYS do this before try to instantiate var like this ==>
if( this.GetComponent(CharacterController) )
mCollider = GetComponent(CharacterController);
else
Debug.Log("Give me a CharacterController");
if( this.GetComponent(MeshFilter) )
m = GetComponent(MeshFilter).mesh;
else
Debug.Log("Give me a MeshFilter");
And you're lucky because if one of your GameObject don't have a CharacterController you'll get the same error :)