I took a bit of a different approach that does one RaycastAll.
void PerformRaycasts() {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] raycastHits = Physics.RaycastAll(ray, maxRaycastDepth).OrderBy(h => h.distance).ToArray();
foreach (RaycastHit hit in raycastHits) {
if (CheckForEnemy(hit)) return; // Specify layer priorities here (order of checks matters)
if (CheckForWalkable(hit)) return;
}
Cursor.SetCursor(unknownCursor, hotSpot, CursorMode.Auto);
}
This is a bit more efficient and deterministic. The Unity doc says that Physics.Raycast “Casts a ray, from point origin, in direction direction, of length maxDistance, against all colliders in the scene”. It will return a indeterminate collider from among all those that pass the layerMask.
Referencing this here as i have a few bugs one of which is fixed in the Q&A by me although the bug is created by me kinda.
Some models not being detected as Enemy.
A : I found the audio trigger i had on my models haad a sphere collider on it that was blocking the raycast to the Enemy script.
A fix which i intend to fix by being implicite about which collider to look for not just any collider.
3D camera causing exceptions.
A: Caused by the raycast being out of range ie too far in distance or skybox.
This i solved in the Q&A code.
NPC healer is now attackable.
A: Caused by that they have an Enemy script. Solution remake the Healer a seperate class from Enemy but will factor it out later as not game breaking. Will psot the code if/when i do it