More compact/efficient way of coding this...

Sorry for the poor thread title, but I didn’t know a better way to explain it.

I have three raycasts. I need to check which raycasts hit something, then add their positions together to average them. With my sloppy coding skills, I’m just resorting to a bunch of if statements and temporary variables to keep track of how many of the rays hit (as you’ll see), but I have this strong feeling that there’s a much better way to code this in javascript/unityscript.
It already works, but I’m just trying to learn some better programming techniques. Excuse my crappy code.

var raycastL : RaycastHit;
var raycastM : RaycastHit;
var raycastR : RaycastHit;
var rayhitL = Physics.Raycast(Vector3(position.x - 9.0, position.y - 4.0,0.0), Vector3(0.0,-1.0,0.0), raycastL, 32.0);
var rayhitM = Physics.Raycast(Vector3(position.x,position.y - 4.0, 0.0), Vector3(0.0,-1.0,0.0), raycastM, 32.0);
var rayhitR = Physics.Raycast(Vector3(position.x + 9.0, position.y - 4.0,0.0), Vector3(0.0,-1.0,0.0), raycastR, 32.0);

if (rayhitM || rayhitL || rayhitR) {
var temp_hits : int = 0;
var temp_pos : float = 0.0;
if (rayhitL) { temp_hits++; temp_pos += raycastL.point.y; }
if (rayhitM) { temp_hits++; temp_pos += raycastM.point.y; }
if (rayhitR) { temp_hits++; temp_pos += raycastR.point.y; }
temp_pos /= temp_hits;


}

You could use an array and loop through it instead of doing each one individually. But, with only three elements, it probably won’t be any shorter, and will actually be fractionally less efficient, since you have to run the loop code in addition to the rest (assuming the compiler isn’t unrolling the loop).

It would be more flexible though, if there’s a chance you were going to add more than three raycasts in the future.

–Eric