I have an FBX model I imported into Unity and then made into a prefab. It has multiple sub-objects (connection pads) on it I want to be able to detect collisions for separately. Basically, I want to be able to wire connection onto each terminal pad in the attached image.
In the prefab I created a separate BoxCollider
for each connection pad. Each connection pad is showing as its own GameObject
in the Unity editor. I gave each pad object a layer called “Pad”.
When I try to Physics.Raycast
with the Pad
layer mask it returns a hit, but hit.collider.transform.position
reports the same for all 3 different pads even though they are separate colliders in separate positions.
When I RaycastAll
one of the results is a Snap Cube
which DOES report the correct position but I can’t target it directly with a layer mask (it doesn’t exist in the editor).
How can I detect collisions directly using a layer mask in the correct location?
As it stands right now the only solution I can figure out is the process the entire group of raycasts, see if one of them is one of the connection pads, then look up the transform position from the other raycast in the group with a Snap Cube
. This is very brittle though because multiple Snap Cube
objects might exist in the future in a more complicated scene.
I can confirm that there is no collider on the parent game object.
Here is the code for the current raycasting that generates the attached console log:
void HandleClick()
{
if (!Input.GetMouseButtonDown(0)) return;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity, (1<<LayerMask.NameToLayer("Pad")))) {
// This is the collider but it reports the position of its parent gameObject.
print($"Raycast(layermask): {hit.collider.gameObject} {hit.collider.transform.position}");
}
foreach(RaycastHit hit2 in Physics.RaycastAll(ray))
{
// One of these hits will actually work but I can't target it directly
print($"RaycastAll: {hit2.collider.gameObject} {hit2.collider.transform.position}");
}
print("");
}
One thing that might be the issue is that I manually created the BoxCollider by using the edit collider interface. It reports a size and center. Perhaps the BoxCollider.transform.position belongs to the parent object? Not sure why it is not associating with the sub-object that shows in the Unity editor.
I tried to get the center
and size
of the collider itself figuring that could be a workaround but doesn’t seem like these are accessible from scripting.
