Raycast never returning true.

Due to the nature of Raycasts having a seemingly infinite variation of inputs, I can’t tell what about my code is wrong. This should turn true when the ray hits an object on the nodes layer. I’ve used a DrawLine to confirm it is hitting, but still only returning false.

public float searchDistance = 10.0f;

LayerMask nodeLayer;

Vector3 linePos;
Ray ray;
RaycastHit hit;

void Start() {
	nodeLayer = 1 << LayerMask.NameToLayer("Nodes");
}

void Update () {
	linePos = transform.position + transform.forward * searchDistance;
	Debug.Log (SearchForNodes ());
	Debug.DrawLine (transform.position, linePos, Color.red, 0, false);
}

bool SearchForNodes() {
	ray.origin = transform.position;
	ray.direction = Vector3.forward;
	return Physics.Raycast (ray, searchDistance, nodeLayer);
}

I’ve tried various combination for Physics.Raycast, replacing ray with (transform.position, Vector3.forward), etc. but it never returns true. I’ve raycasted successfully before, just without the distance thing, so I think that’s the issue (I’ve gotten masks to work before), but the DrawLine says it’s long enough, and I’ve tried ridiculously high searchDistances to no avail.

The problem is that linePos uses transform.forward, while ray.direction uses Vector3.forward. The first is local forward and the latter is global forward. You should change it to transform.forward.

Also, I have not tried Ray type, you might need to put the position and direction variables instead of the ray variable.

If it does not work, check your layers.