在网上看到各路大神的解释,终于明白了,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是干嘛的。
官网解释:
Given a layer name, returns the layer index as defined by either a Builtin or a User Layer in the Tag Manager.
是返回的该名字所定义的层的层索引,注意是从0开始。