Changing LayerMask

If I have an existing LayerMask defined through the inspector and I want to keep all the layers already included but include or exclude 1 extra layer through scripting, how do I do this?

I tried this, but it includes all layers (not only the ones in the mask) and then excludes the one I want.

layers = layers | ~(1 << LayerMask.NameToLayer(“LayerToExclude”));

Remove the “~”.

This will include the extra layer correctly, however what if I want to exclude it and keep only the existing layers in the mask?

layers = layers & ~layerToExclude

1 Like

Works, thanks!