Physics.RaycastAll Problems

Hi Guys

I’m having trouble understanding the ORDER a ray casts returns all hits. Basically the raycast works and returns an array populated with the many gameobjects it passed through however the ORDER of the actual gameobjects in the array is not consistent or reliable and not in the order I intended.

I’ve attached a picture which outlines my situation (located at the bottom).

My code in it’s basic form:

var hits : RaycastHit[];
hits = Physics.RaycastAll(goTopMostGameObject.transform.position, goTopMostGameObject.transform.forward, Mathf.Infinity);

for (var i = 0; i < hits.length; i++)
{
	Debug.Log(i.ToString() + ", " + hits[i].collider.gameObject.name + ", " + hits[i].collider.gameObject.tag);
}

I was hoping the raycast would order the gameobjects in the hits array in the same order the raycast passes through the gameobjects in the scene, … however this isn’t the case. If it ordered the gameobjects accordingly then I could compare the top gameobject with the one directly beneath it and check for gameobjects that have the same tag.

Based on my image below I though I’d get the following results (for clarity I’m not using actual code)
hits(typeA, typeB, typeA, typeC, typeC);
Instead it could order them this way:
hits(typeB, typeA, typeC, typeA, typeC);

Originally I had the gameobjects closer and I though the box colliders might be overlapping which I thought might cause the unpredictible order however I did move them apart more and reduced the size (z) of the Box collider without luck.

Any suggestions?

Cheers
Dean

Can’t really answer this, but just a warning : if I’m not mistaking, RaycastAll returns an array, and it will increase the heap and cause GC to kick in after a while. So avoid using it as much as possible.

Hi,

I have pretty much the same problem with RaycastAll in the FingerManager from the wiki. I posted this on the support forum.

http://forum.unity3d.com/viewtopic.php?t=52246

Andeee posted an answer to this, that actually describes the detection of a target object. But this is not useful for me (I’ve got several target objects but need to know the first one that is hit), basically knowing the reliable way the array is built would be fine but the array seems to be unpredicatble. I attached a unitypackage in my post demonstrating that it seems to be related to camera rotation. I think I will drop the FingerManager as I don’t have any clear answers until today.

Yeah I still haven’t figured it out however thanks for that link (synapsemassage) and thanks for the heads up about the memory issue (Smag).

Cheers

You can compare the distance variable in the RaycastHit structure.

  1. do raycastall
  2. sort the list according the distance variable in RaycastHit