Unity:Layer层的使用

1、Layer 简述

官网:Layers are most commonly used by Cameras to render only a part of the scene, and by Lights to illuminate only parts of the scene. But they can also be used by raycasting to selectively ignore colliders or to create collisions
中文:Layers通常被摄像机用来渲染部分场景,和灯光照射部分场景使用。但是它们也可以用来做射线检测时忽略一些collder或Collision使用

2、Layer 获取和开启

//通过名称获取

 int layer = LayerMask.NameToLayer("Enemy");

//Layer 开启和关闭写法

//开启并获取Enemy Layer层
int layerMask = 1 << LayerMask.NameToLayer("Enemy"); 

//关闭并获取Enemy Layer层
int layerMask = 0 << LayerMask.NameToLayer("Enemy"); 

//表示关闭Enemy和Player Layer层。
LayerMask mask = 0<

3、批量获取GameObject 底下子节点的Layer层

 private int[] GetGoLayers(GameObject go)
 {
      try
      {
          var childTransform= go.GetComponentsInChildren();
          int[] layers = new int[childTransform.Length];
          for (int i = 0; i < childTransform.Length; i++)
          {
              layers[i] = childTransform[i].gameObject.layer;
          }
          return layers;
      }
      catch (Exception e)
      {
              Debug.Log(e);
      }
  }

4、批量设置GameObject 子节点同一个Layer层

  private void SetGoLayers(GameObject go, int layer)
  {
       try
       {
           var childrenTrans = go.GetComponentsInChildren();
           for (int i = 0; i < childrenTrans.Length; i++)
           {
               childrenTrans[i].gameObject.layer = layer;
           }
       }
       catch (Exception e)
       {
           Debug.LogError(e.ToString());
       }
   }

文章来源:http://www.lsk-ww.cn:8080

你可能感兴趣的:(Unity,Layer)