Array Index Out of Range Error with OnCollisionStay

I’m having an issue with this function:

function OnCollisionStay(collision: Collision){
	if(!dead){	
		if(collision.gameObject.tag == "ground"){
			var contact:ContactPoint = collision.contacts[0];
    		rotation = Quaternion.FromToRotation(Vector3.up, contact.normal);
		}
	}
}

I’m using this to rotate my enemies to the ground in a 2d game. It works great most of the time, but every so often I get an “Array Index out of range” error on this line:

var contact:ContactPoint = collision.contacts[0];

Any ideas what is causing this? The gameobjects have a sphere collider. Thanks a lot for any help on this.

I would assume that there’s nothing in collision.contacts when that happens, so you should check that the length of the array is at least 1 before accessing it.

–Eric

Thanks Eric that fixed it.