How do I ask if RaycastHit returns null?

I am trying to ask if my RaycastHit didnt hit anything.
Heres my script:
var curSelection : GameObject;

var object : GameObject;

function Update () {
	var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hit : RaycastHit;
	if(Input.GetMouseButtonDown(0)){
		if (Physics.Raycast (ray, hit, 100)){
			if(hit == null){
				object = null;
			}
        }
	}
}

whats wrong with it?

You’re already testing if the Raycast hit something with the if(Pysics.Raycast) statement.

How it should look:

var curSelection : GameObject;

var object : GameObject;

function Update () {
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    var hit : RaycastHit;
    if(Input.GetMouseButtonDown(0)){
       if (Physics.Raycast (ray, hit, 100)){
            // if not null, do stuff.
        }
        else // If Raycast did not return anything
        {
            object = null;
        }
    }
}

The problem is that by saying;

if (Physics.Raycast (ray, hit, 100)){
    etc. etc...

you are basically asking "If the raycast hit something, see if the raycast didn't hit anything." I expect it could be fixed by simply using 'else'.

if(Input.GetMouseButtonDown(0)){
    if (Physics.Raycast (ray, hit, 100)){
        // Do stuff for rays that aren't null.
    }
    else {
        // Do stuff for rays that are null.
    }
}

Or perhaps;

    if (!Physics.Raycast (ray, hit, 100)){
    ...

Well, I think those make sense anyway. I'm tired and haven't tested this, so do bear in mind that I may be inadvertently spouting a load of twaddle.

Edit - Dammit, beaten to it! At least we both gave the same answer though. :D

You can test the normal, too, I think. If it’s Vector3.zero, the Raycast didn’t hit anything.
(C#:slight_smile:

Physics.Raycast(Ray,out Hit,maxRayDistance,LayerMask.GetMask(Mask));
someObject.Hit=Hit;
//  [... some coding later]
if(someObject.Hit.normal!=Vector3.zero){
//  The Raycast hit something!
}