stack overflow exception


I am doing an app in which I have to simulate and explain light’s behavior when it hits various objects:
Filters, Mirrors, Prisms…
I have one generic script for Filter, one for Mirror, one for prism…
the script is instantiated as many times are those objects are duplicated.

I am using raycast to simulate the light beam. the beam is casted from source. On raycasthit(when the beam hits the object), light information is transmitted using sendMessage to the script attached to hit object.The script will use this information to cast a new ray and so on …

I have no problem for the mirror script. But the filter script has a problem:
I am getting a stack overflow exception message and I can’t figure out why.

function HitByRaycast(receivedLightInfo) {

	// Retrieving Light Info
    var incomingVec = receivedLightInfo[0];
    var hit = receivedLightInfo[1];
    var inColor = receivedLightInfo[2];
    //Specifying Filter's color property
	var filterColor =renderer.material.GetColor ("_Color");   
    var outColor = inColor - (Color.white- Color(filterColor.r , filterColor.g , filterColor.b, 1));
    //building the reflection beam
    var reflectVec = Vector3.Reflect(incomingVec, hit.normal);	
    var reflectHit: RaycastHit;
	var reflectRay = Ray(hit.point, reflectVec);
	var reflectRayCast = Physics.Raycast(reflectRay, reflectHit,1000);
	//displaying the filtered light beam
	if (reflectRayCast != true)
			Debug.DrawRay(hit.point, reflectVec*1000, outColor);
	else if (reflectRayCast==true)
			Debug.DrawLine(hit.point, reflectHit.point, outColor);
			//passing light information to the hit object
			var lightInfo = new Array (reflectVec, reflectHit, outColor);


The error means you’re getting an infinite loop (a standard infinite loop merely freezes. If you have function calls, you run out of space and get Stack Overflow instead.)

You’re probably getting a circle of bounces, or an object is hitting and casting from itself over and over.

Adding Debug.Log("hit "' can help, but debugs don’t always get printed on crashes. A common trick is to throw in a bounce counter, and quit at 20 or so.

My the filter object is just a quad, so at first glance, it was a bit hard to imagine that the object could raycasthit itself.
But you pointed out something right and that’s indeed what is happening.
I am trying to solve the issue by offsetting slightly the the new raycast origin from the raycasthit.

:slight_smile: Thanks