Raycast not working

I’ve got a scene with gameobjects with mesh colliders and layer set to a custom layer called “outer space”.
I try to shoot rays from the camera to these objects, so I have a script attached to the camera where I do:

if (Physics.Raycast(transform.position, transform.forward, hit))
//...

and that works,
but when I do:

if (Physics.Raycast(transform.position, transform.forward, hit, Mathf.Infinity, LayerMask.NameToLayer("outer space")))

then I get no hit.

Any idea why it doesn’t work ?
(there are other objects in the scene with a different layer, which I do not want the raycast to hit)

Instead of just:

LayerMask.NameToLayer("outer space")

Try this:

1 << LayerMask.NameToLayer("outer space")

Reason is, NameToLayer() returns a layer index, but Raycast() wants a layer mask. The two are not quite the same thing. To collide against layer 9, you want the 9th bit of your layer mask set, which we can get by bitwise shifting: 1 << 9.

For newer versions of Unity you can use LayerMask.GetMask("outer space") instead of the bitshift method suggested by @rutter.