I am converting a component of the 2D Gameplay Tutorial to C#, but I came across a double less-than symbol. I am not sure what it does and I was unable to find information about it by searching the forums and web. The line in question is this:
var bodyLayerMask = 1 << body.gameObject.layer;
My guess is that it produces a boolean value, but I am not sure. So, who knows what that symbol does so I can convert it to C#?
It’s called bit shifting and it’s used in binary.
It moves the Bits one to the right (left?).
For starters, Computers use binary.
This means 6 = 00000110
65 = 01000001
255 = 11111110
etc…
You’ll have to look up Binary and how it works if need more info on that.
What bitshifting does is shift all values to the right.
so 00001000 << 1 = 00010000
and 01010101 << 1 = 10101010
and 00001111 << 2 = 00111100
and 00000001 << 5 = 00100000
The value on the right is the amount to move by.
Now layers use a system of flags. Flags are a data type like bool or float or int, but they have a special functionality.
Flags are a set of properties that can be either all on or all off, or turning on or off each flag in a set individually.
Flags use bits to represent the individual flags:
Each 1 or 0 is a flag on or off.
Bit shifting in this case takes a 1 (00000001) and moves it over the amount that you layer flag is set to (if 4 it would be 00010000) and thus marking that flag as being in use.
I am familiar with binary. And thanks for the explanation. I ended up searching for C# operators and I found that there. I dunno why I didn’t search for that beforehand. Anyway, I assume now that I need to set the variable type to the same type that was shifted, right? In this case body.gameObject.layer is an int value so the new line of code would be
int bodyLayerMask = 1 << body.gameObject.layer;
Right?
Yes.
It’s a bit of odd functionality, but the Layer that’s set on the object is a small integer that represents the flag number, but the Raycast takes in an int flags that is the bitshifted value. The reason for this is that an object can only be on one layer so it uses a simple int, but the Raycast can be for many layers so it needs to use the int flags.
This shows the bitshifted value being set as an int.
Interesting. How did you find this out? Is there documentation about how the layers and raycasting work with Unity, or is that just something commonly used in physics engines?
well it has nothin to do with unity, but
in math it means much bigger/smaller than… 
Here’s a little utility script I wrote if you don’t want to bother with bitshifting yourself. (Miniscule tradeoff of speed for readability)
http://www.unifycommunity.com/wiki/index.php?title=Layers
Thanks for the script. I am just converting the files to C# for now, but if I need to rewrite them to match any functionality I might need maybe I will use it.