Search Unity

Does a well known LayerMask utility/library exist?

Discussion in 'Scripting' started by Pumpk1nz, Jan 16, 2022.

  1. Pumpk1nz

    Pumpk1nz

    Joined:
    Dec 31, 2020
    Posts:
    1
    I understand the bit shifting, masking etc are necessary for efficient use of layers, but what I don't understand is why, as far as I can tell, there isn't a utility to help developers create layer masks without having to think about bit shifting. It seems to me like there would be a large use case for developers to create/modify layer masks in code by adding/removing layers, or creating masks from all layers except a list, etc. I've tried googling for something like this, and I'm not finding anything. I'm considering writing one myself and publishing it in a git repository, but I don't want to bother if someone else has already done it. Anybody know of anything like this?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,459
    A library to deal with bits? Seems a bit overkill given that a LayerMask is just an int and you're saying you want a method call to add/remove a bit. It's probably not available because it's so trivial I guess as it'd be a so few lines of code. Note that Unity already provides most of what I believe you'd need via GetMask.

    Code (CSharp):
    1. LayerMask AddLayer(int layer, LayerMask mask)
    2. {
    3.     return mask.value | (1 << layer);
    4. }
    5.  
    6. LayerMask RemoveLayer(int layer, LayerMask mask)
    7. {
    8.     return mask.value &= ~(1 << layer);
    9. }
    10.  
    Also, I think the main use-case is where a layer mask is created once and then used more statically so expose the LayerMask to the inspector via a script and configure it there. Dynamically manipulating this in ways you suggest is very specific to your project i.e. using layers except those in a list. That code added to the above would be a few extra lines of code.

    All that said, create a Github account and add your own and see if others find it useful. I'd be happy to refer to it if I were to see it asked again.
     
    Bunny83 likes this.