NullRefException in RaycastAll

Ok, so I’m chugging through Eteeski’s AI Pathfinding tutorials, trying to make the enemy’s body stay on the ground, but I’m hitting an error that only appears when I run it in play mode:

NullReferenceException: Object reference not set to an instance of an object
Boo.Lang.Runtime.RuntimeServices.InvokeBinaryOperator (System.String operatorName, System.Object lhs, System.Object rhs)
GenericEnemyBody.Update () (at Assets/Scripts/GenericEnemyBody.js:21)

And here is my code:

var moveDamp : float = .1;
var turnSpeed : float = 10;
var parentToFollow : Transform;

var velocityX : float;
var velocityZ : float;

function Awake () 
	parentToFollow = transform.parent;
	transform.parent = null;

function Update () 
	transform.position.x = Mathf.SmoothDamp(transform.position.x, parentToFollow.position.x, velocityX, moveDamp);
	transform.position.z = Mathf.SmoothDamp(transform.position.x, parentToFollow.position.z, velocityZ, moveDamp);
	transform.rotation = Quaternion.Lerp(transform.rotation, parentToFollow.rotation, turnSpeed * Time.deltaTime);
	var hits : RaycastHit[];
	hits = Physics.RaycastAll(Ray(transform.positon + Vector3(0, 100, 0), (Vector3.up * -1)));

	for(var i : int = 0; i < hits.length; i++)
		var hit : RaycastHit = hits*;*
  •  if(hit.transform.gameObject == parentToFollow.gameObject.GetComponent(GenericEnemyBehavior).currentCell)*
  •  {*
  •  	transform.position.y = hit.point.y;*
  •  }*
  • }*

Thanks for the help!!!

Can you please try to call this overload instead of the one you used. You can pass float.MaxValue to distance parameter. I remember I had some issues with raycast before and I suspected that it was Unity’s internal bug. Please try this and let me know if it help.

RaycastAll(ray: Ray, distance: float)

without knowing which line these errors occur on here is my stab in the dark:

  • does this object even have a parent to begin with (why is this component that is being gotten n=inf times an Update() not being cached if the object is just a parent)
  • does the list have anything in it? is the list null?
  • does the parent have this component you are trying to get n=inf times