LayerMask使用

在网上看到各路大神的解释,终于明白了,LayerMask实际上是一个位码操作,在Unity3d中Layers一共有32层,这个是不能增加或者减少的:


摘自官网:

Layers are used throughout Unity as a way to create groups of objects that share particular characteristics (see this page for further details). Layers are primarily used to restrict operations such as raycasting or rendering so that they are only applied to the groups of objects that are relevant. In the manager, the first eight layers are defaults used by Unity and are not editable. However, layers from 8 to 31 can be given custom names just by typing in the appropriate text box. Note that unlike tags, the number of layers cannot be increased.


所以那个LayerMask实际上是用Int32的32个位来表示每个层级,当这个位为1时表示使用这个层,为0时表示不用这个层。

看例子:

void Awake ()
{
weapScript = gameObject.GetComponent<WeaponBehavior> ();
GameObject GO = new GameObject ();
GO.AddComponent<GUITexture>();
GO.guiTexture.texture = scopeTexture;
GO.layer = LayerMask.NameToLayer ("NGUI");
//scopeTexture.
}

这一句实际上表示射线查询只在"NGUI"所在这个层级查找。


再来看看NameToLayer是干嘛的。

官网解释:

Description

Given a layer name, returns the layer index as defined by either a Builtin or a User Layer in the Tag Manager.

是返回的该名字所定义的层的层索引,注意是从0开始。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Layer MaskUnity中用于指定物体所属层级的一种方式。在使用射线检测时,你可以使用Layer Mask来指定射线可以检测到哪些层级的物体。 在Unity中,你可以通过以下步骤设置物体的层级和Layer Mask: 1. 设置物体的层级:在场景中选中需要设置层级的物体,在检视面板中找到Layer属性,可以选择或新建一个层级。 2. 设置Layer Mask:在编写射线检测脚本时,你可以使用Layer Mask来指定射线可以检测到哪些层级的物体。你可以在代码中使用以下方式设置Layer Mask: ```csharp public LayerMask layerMask; void Update() { // 检测前方物体 RaycastHit hit; if (Physics.Raycast(transform.position, transform.forward, out hit, Mathf.Infinity, layerMask)) { // 获取检测到的物体信息 Debug.Log(hit.collider.gameObject.name); } } ``` 在这个示例中,我们定义了一个LayerMask类型的变量`layerMask`,并在射线检测时使用该变量指定射线可以检测到哪些层级的物体。你可以在检视面板中为这个变量指定需要检测的层级,也可以在代码中使用`LayerMask.GetMask()`方法来指定需要检测的层级。 ```csharp public LayerMask layerMask = LayerMask.GetMask("Ground", "Obstacle"); void Update() { // 检测前方物体 RaycastHit hit; if (Physics.Raycast(transform.position, transform.forward, out hit, Mathf.Infinity, layerMask)) { // 获取检测到的物体信息 Debug.Log(hit.collider.gameObject.name); } } ``` 在这个示例中,我们使用`LayerMask.GetMask()`方法来指定射线可以检测到名为"Ground"和"Obstacle"的层级。 希望这个回答能够帮助你理解Layer Mask的概念和使用方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值