How do I check if RaycastAll hits nothing

RaycastHit Hits = Physics.RaycastAll(RayLine, Range);
RaycastHit FinalHit;

		float LastDistance = 0;
		foreach(RaycastHit Hit in Hits)
		{
			if(Hit.transform != transform && (LastDistance == 0 || Hit.distance < LastDistance))
			{
				FinalHit = Hit;
				LastDistance = Hit.distance;
			}
		}
		
		if(!FinalHit) // ERROR LINE <<<<<<<<<<<<<<<<<<<<<<<<<<<<
		{
			Hit();
		}

/*2 errors on one line:
error CS0165: Use of unassigned local variable `FinalHit'
error CS0023: The `!' operator cannot be applied to operand of type `UnityEngine.RaycastHit'*/

Seems like FinalHit = Hit isn’t assigning the FinalHit variable. How do I solve it besides by assigning the Hit.transform to FinalHit? And how do I check if FinalHit is null/empty?

EDIT:

I SOLVE THE USE OF UNASSIGNED VARIABLE PROBLEM BY DOING

		RaycastHit FinalHit = new RaycastHit();

2 Answers

2

In a “if” statement, you need to test a boolean. Here you try to test a RaycastHit, so this does not work.

You can check a boolean valued if a raycast worked :

RaycastHit[] Hits = Physics.RaycastAll(RayLine, Range);
RaycastHit FinalHit;
boolean isHit = false;
 
float LastDistance = 0;
foreach(RaycastHit Hit in Hits)
{
    if(Hit.transform != transform && (LastDistance == 0 || Hit.distance < LastDistance))
    {
        isHit = true;
        FinalHit = Hit;
        LastDistance = Hit.distance;
    }
}
 
if(!isHit)
{
    Hit();
}

Don’t forget to revalue “isHit” to false when you don’t need it anymore. If you don’t use “FinalHit” in the “Hit” method, there is no use at all now.

Yeah thanks guys, looks like I have no way of doing !FinalHit, I am currently doing it the same way as KiraSensei's way

Just check if the array has a Length of 0.