Tags和Layers分别表示是Unity引擎里面的标签和层,他们都是用来对GameObject进行标识的属性,Tags常用于单个GameObject,Layers常用于一组的GameObject。添加Tags和Layers的操作如下:

"Edit" -> "Project Settings" -> "Tags and Layers"来打开设置面板。

tag可以理解为一类元素的标记,如hero、enemy、apple-tree等。通过设置tag,可以方便地通过GameObject.FindWithTag()来寻找对象。GameObject.FindWithTag()只返回一个对象,要想获取多个tag为某值的对象,GameObject.FindGameObjectsWithTag()。

每个GameObject的Inspector面板最上方都也有个Layer选项,就在Tag旁边,unity已经有了几个层,我们新建个层,也叫UI,点击Add Layer,可以看到从Layer0到Layer7都灰掉了,那是不能用的,从第八个起可以用,Layer和tag还有一个很大的区别就是layer最多只能有32个层。

在使用过程中,使用Culling Mask、Layer Mask的地方实际指的就是layer。下面我们来看一段使用layer来检测碰撞的代码:

Ray ray1 = nguiCamera.camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit1;
LayerMask mask = 1 << LayerMask.NameToLayer("UI"); if (Physics.Raycast(ray1, out hit1, 600, mask.value))
{ return;
} 

LayerMask的NameToLayer是通过层的名称返回该层的索引,如果是8,然后1<<8换算成LayerMask值,再用LayerMask的value就可以了。注意也必须设置collider才能接收碰撞,这里才能判断到。LayerMask实际上是一个位码操作,在Unity中Layers一共有32层,这个是不能增加或者减少的:     1 << LayerMask.NameToLayer("UI") 这一句实际上表示射线查询只在UI所在这个层级查找是返回的该名字所定义的层的层索引,注意是从0开始。

下面我们来看一个玩家控制的脚本,利用 Physics2D.Linecast检测物体是否碰撞到地面。

using UnityEngine;
using System.Collections;public class PlayerControl : MonoBehaviour
{[HideInInspector]public bool facingRight = true;            // For determining which way the player is currently facing.
    [HideInInspector]public bool jump = false;                // Condition for whether the player should jump.public float moveForce = 365f;            // Amount of force added to move the player left and right.public float maxSpeed = 5f;                // The fastest the player can travel in the x axis.public AudioClip[] jumpClips;            // Array of clips for when the player jumps.public float jumpForce = 1000f;            // Amount of force added when the player jumps.public AudioClip[] taunts;                // Array of clips for when the player taunts.public float tauntProbability = 50f;    // Chance of a taunt happening.public float tauntDelay = 1f;            // Delay for when the taunt should happen.private int tauntIndex;                    // The index of the taunts array indicating the most recent taunt.private Transform groundCheck;            // A position marking where to check if the player is grounded.private bool grounded = false;            // Whether or not the player is grounded.private Animator anim;                    // Reference to the player's animator component.void Awake(){// Setting up references.// 在子对象里面找到groundCheckgroundCheck = transform.Find("groundCheck");// 获取当前的动画控制器anim = GetComponent<Animator>();}void Update(){// 是为能随时检测到groundCheck这个物体,添加一个名叫Ground的Layer,然后把场景中的所有代表地面的物体的Layer设为Ground// 这里用到了2D射线检测Physics2D.Linecast()// LayerMask实际上是一个位码操作,在Unity3d中Layers一共有32层,这个是不能增加或者减少的:// 1 << LayerMask.NameToLayer("Ground") 这一句实际上表示射线查询只在Ground所在这个层级查找 是返回的该名字所定义的层的层索引,注意是从0开始// 每个GameObject的Inspector面板最上方都也有个Layer选项,就在Tag旁边,unity3d已经有了几个层,我们新建个层,也叫UI,点击Add Layer,可以看到从Layer0到Layer7都灰掉了,那是不能用的,从第八个起可以用,所以在第八个建个UI的层。// 一般情况下我们只用前两个参数,distance表示射线距离,默认是无限远,重点是最后一个参数layerMask,专门处理layer过滤的,是个整型,怎么用呢,是靠layer的二进制位来操作的// LayerMask的NameToLayer是通过层的名称返回该层的索引,这里是8,然后1<<8换算成LayerMask值,再用LayerMask的value就可以了。// 注意也必须设置collider才能接收碰撞,这里才能判断到。grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));  // If the jump button is pressed and the player is grounded then the player should jump.// 如果点击了跳的按键,并且已经着陆,那么就可以跳起来if(Input.GetButtonDown("Jump") && grounded)jump = true;}// 因为主角游戏对象要使用到刚体力,所以一定要写在FixedUpdate里面,不能放在Update上void FixedUpdate (){// Cache the horizontal input.// 换取水平方向的移动距离float h = Input.GetAxis("Horizontal");// The Speed animator parameter is set to the absolute value of the horizontal input.// 设置动画的速度变量anim.SetFloat("Speed", Mathf.Abs(h));// 给物体添加一个水平的力,让它移动的时候会产生惯性的效果// If the player is changing direction (h has a different sign to velocity.x) or hasn't reached maxSpeed yet...// 如果速度小于最大的速度 if(h * rigidbody2D.velocity.x < maxSpeed)// ... add a force to the player.rigidbody2D.AddForce(Vector2.right * h * moveForce);// If the player's horizontal velocity is greater than the maxSpeed...if(Mathf.Abs(rigidbody2D.velocity.x) > maxSpeed)// ... set the player's velocity to the maxSpeed in the x axis.rigidbody2D.velocity = new Vector2(Mathf.Sign(rigidbody2D.velocity.x) * maxSpeed, rigidbody2D.velocity.y);// 转身// If the input is moving the player right and the player is facing left...if(h > 0 && !facingRight)// ... flip the player.
            Flip();// Otherwise if the input is moving the player left and the player is facing right...else if(h < 0 && facingRight)// ... flip the player.
            Flip();// If the player should jump...if(jump){// Set the Jump animator trigger parameter.// 触发跳的动画anim.SetTrigger("Jump");// Play a random jump audio clip.int i = Random.Range(0, jumpClips.Length);AudioSource.PlayClipAtPoint(jumpClips[i], transform.position);// Add a vertical force to the player.// 添加一个垂直的力rigidbody2D.AddForce(new Vector2(0f, jumpForce));// Make sure the player can't jump again until the jump conditions from Update are satisfied.jump = false;}}// 转身void Flip (){// Switch the way the player is labelled as facing.facingRight = !facingRight;// Multiply the player's x local scale by -1.Vector3 theScale = transform.localScale;theScale.x *= -1;transform.localScale = theScale;}public IEnumerator Taunt(){// Check the random chance of taunting.float tauntChance = Random.Range(0f, 100f);if(tauntChance > tauntProbability){// Wait for tauntDelay number of seconds.yield return new WaitForSeconds(tauntDelay);// If there is no clip currently playing.if(!audio.isPlaying){// Choose a random, but different taunt.tauntIndex = TauntRandom();// Play the new taunt.audio.clip = taunts[tauntIndex];audio.Play();}}}int TauntRandom(){// Choose a random index of the taunts array.int i = Random.Range(0, taunts.Length);// If it's the same as the previous taunt...if(i == tauntIndex)// ... try another random taunt.return TauntRandom();else// Otherwise return this index.return i;}
}

转载于:https://www.cnblogs.com/qiuxiangmuyu/p/5826418.html

【Unity3D】Tags和Layers相关推荐

  1. 【Unity3D游戏开发】基础知识之Tags和Layers (三二)

    Tags和Layers分别表示是Unity引擎里面的标签和层,他们都是用来对GameObject进行标识的属性,Tags常用于单个GameObject,Layers常用于一组的GameObject.添 ...

  2. Unity 1.Roll a Ball

    目录 基础资料 小球脚本:监听键盘使小球移动 摄像机脚本:关联小球与摄像头(镜头不翻滚) 物体旋转脚本 Debug: 存储计分,并显示Text: Build 完整项目下载 基础资料 Unity官方教程 ...

  3. Unity 制作小地图

    原文地址:http://forum.china.unity3d.com/thread-17192-1-1.html 小地图的基本概念 众所周知,小地图(或雷达)是用于显示周围环境信息的.首先,小地图是 ...

  4. [Unity]2D打飞机游戏

    今天带来一个在自学Unity3D过程中写的第一个2D打飞机小游戏.代码写得不好,功能也很少,主要是为了记录学习心得,也希望各位能够多给些指导.后续应该会有优化和完善游戏功能. 闲话不多说,先来分析下游 ...

  5. Unity流水账2:视频播放之Video Player

    VideoPlayer组件   使用VideoPlayer组件可以将视频文件附加到GameObjecs,并在运行时,在GameObject的Texture上播放它们.   默认情况下,Video Pl ...

  6. Unity 2D游戏开发教程之游戏中精灵的跳跃状态

    Unity 2D游戏开发教程之游戏中精灵的跳跃状态 精灵的跳跃状态 为了让游戏中的精灵有更大的活动范围,上一节为游戏场景添加了多个地面,于是精灵可以从高的地面移动到低的地面处,如图2-14所示.但是却 ...

  7. Unity中Camera的Clear flags,Culling Mask,Depth参数

    1.Clear flags参数 它的作用相当于Directx中clear()函数. 这个参数有四个可选值:Skybox,Solid Color,Depth only,Don't clear. (1)指 ...

  8. Unity 2D教程: 滚动,场景和音效

    http://www.tairan.com/archives/7074 原文地址:http://www.raywenderlich.com/71029/unity-4-3-2d-tutorial-sc ...

  9. Unity-Unity编辑器Part5

    场景(Scene) 场景包含游戏对象.它们可以用来创建主菜单或者其他任何东西.将每个独特的场景文件视为一个独特的层次.在每一个场景中,你会把你的环境.障碍和装饰都放置在你的游戏中. 一个新的空白场景, ...

最新文章

  1. JDBC数据源连接池(1)---DBCP
  2. python软件代码示例-Python学习示例源码
  3. *dev=filp-private_data;这一句的理解
  4. 顺序容器及其常用函数
  5. java猜字母讲解_java_猜字母游戏
  6. vim 中代码的折叠和打开
  7. phpcmsV9留言插件提交后返回上一页实现方法
  8. 软件测试三种错误的是,软件测试中的三种排错方法(知识篇)
  9. 湖南省区块链协会成立
  10. 智力题 - 士兵编队与传讯员
  11. 连接MYSQL数据库,报1130错误的解决方法
  12. 2021 ICPC Asia Jinan Regional Contest-J Determinant(取模高斯消元)
  13. jstack简单使用,定位死循环、线程阻塞、死锁等问题
  14. 基于IdentityServer4的单点登录——IdentityServer
  15. 编译安装Nginx以及配置运行Drupal 8,实现上传进度功能
  16. 计算机中缺少mfc100.dll怎么办,大师为你细说win7系统启动程序提示计算机中丢失mfc100u.dll的解决技巧...
  17. 精益软件开发(Lean Software Development)
  18. J - R u really ready?(CCRC 18)动态规划
  19. html展开折叠菜单,纯CSS竖向滑动展开折叠菜单
  20. linux latex 英文字体,LaTeX 中的一些英文字体

热门文章

  1. 文件上传linux服务器,Linux 文件上传Linux服务器
  2. uniapp 页面渲染完成
  3. 汇编 div_Solidity汇编开发简明教程
  4. 灰色的rgb值_一行代码实现图片的灰色效果
  5. 基于ssm的个人博客_基于 CentOS7 搭建 WordPress 个人博客
  6. css border 虚线间距_【前端冷知识】CSS如何实现虚线框动画
  7. postman下载教程linux,linux 安装postman
  8. vue事件总线_[面试] 聊聊你对 Vue.js 框架的理解
  9. 牛逼!Python错误、异常和模块(长文系列第4篇)
  10. 肝!打造一款高逼格的Vim神器