Search Unity

Layermask: Is there a simple way to do that?

Discussion in 'Scripting' started by Marscaleb, Aug 22, 2018.

  1. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    I'm writing some code to check for overlapping objects. It is reasonable for me to use a layer mask to cull the objects to check.
    But as I think about it, in this particular case I'm only searching for objects in one specific layer. That's got me thinking, is there an easy way to just specify that one layer? Otherwise I'd have to create a variable to be a layer mask and then set it in the editor. That becomes one more variable that could screw things up if I neglect to set it in any object using this script. Plus another variable for the game to track, slightly increasing the game's ovehead.
    It sounds like it would be better if I could just have my script specify one single layer directly in the code instead of creating a whole layer mask. Is there a way to do this?
     
  2. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    EDIT: Whoops, I got too excited and posted about layer masks before reading your whole question. You cannot exactly reference a layer and run physics against it, but passing a layermask into a physics function is basically as optimized as what you're asking. Don't forget you can store your LayerMask as an int for re-use. I'll leave my layer mask rant below in case anyone is interested.



    If you want automatic built-in unity physics to filter by layer, in Unity go to "Edit->Project Settings->Physics" (or Physics2D) and use the check boxes in the inspector to determine which layers will detect collisions with which other layers.

    If you want physics in code to filter by layer, pass a LayerMask (int) as a parameter in your physics functions. You can get a LayerMask if you know the layer name by using
    LayerMask.NameToLayer(string)
    . If you want to check against multiple layers, you can combine layers using the 'or' bitwise operator like this
    LayerMask.NameToLayer("Layer 1") | LayerMask.NameToLayer("Layer 2")


    Hope this helps!