Unity 实用的方法

一、延迟销毁游戏对象

  默认情况下,使用 Destroy() 方法会立即销毁游戏对象,如果想延迟一段时间再销毁,可以在这个方法中传递一个时间参数。

1    Destroy(gameObject, 2.5f);

  这段代码实现的效果就是经过 2.5 秒后销毁游戏对象。

二、获取一个随机布尔值

  我们知道 Random.value 能够返回 0~1 之间的随机数,所以让此随机数与 0.5f 进行比较,就能够获取一个随机的布尔值 True 或者 False

1    bool true_Or_Flase = (Random.value > 0.5f);

三、协程嵌套

  在一个协程里面开启另外一个协程,可以使用以下方法:

 1     void Start()
 2     {
 3         StartCoroutine(FirstCorout());
 4     }
 5 
 6     IEnumerator FirstCorout()
 7     {
 8         yield return StartCoroutine(SecondCorout());
 9     }
10 
11     IEnumerator SecondCorout()
12     {
13         yield return 0;
14     }

四、快速比较距离

  将两点之间的距离与一个固定距离进行比较时,可使两点相减然后取平方(即 sqrMagnitude ),然后用该值与某个距离值的平方进行比较。

1    if((pointA-pointB).sqrMagnitude < dist * dist)
2    {
3 
4    }

  相比使用 Vector3.Distance 方法获取两点之间距离,然后与给定的距离值进行比较,sqrMagnitude 方法省去了 Vector3.Distance 方法求平方根的操作,所以在执行速度上比 Vector3.Distance 方法快。

1    if (Vector3.Distance(pointA, pointB) < dist)
2    {
3 
4    }

五、在Inspector面板中显示私有变量

  将私有变量标记为 SerializeField,可在 Inspector 面板中进行显示。

六、在Inspector面板中隐藏公有变量

  如果不希望在 Inspector 面板中显示公有变量,可将其标记为 [HideInInspector]

七、CompareTag方法

  当对游戏对象的 Tag 进行比对的时候,可使用 CompareTag 方法。

1    if (gameObject.CompareTag("Player"))
2    {
3 
4    }

  从性能上考虑,使用双等号进行判断比使用 CompareTag 方法更耗费性能。

1    if (gameObject.tag == "Player")
2    {
3 
4    }

八、高亮显示Debug.Log对应的游戏对象

  当使用 Debug.Log 方法输出信息时,可将 gameObject 作为此方法的第二个参数。

1     void Start()
2     {
3         Debug.Log("This is a test", gameObject);
4     }

  当程序运行时,点击 Console 面板中对应的输出信息,就可以在 Hierarchy 面板中高亮显示挂载了此脚本的游戏对象。

九、WaitForSecondsRealtime

  当时间缩放为 0 时(即 Time.timeScale=0f ),waitForSeconds 方法将不会停止等待,后续代码也不会执行,此时可使用 WaitForSecondsRealtime 方法。

1   Time.timeScale = 0f;
2   yield return new WaitForSecondsRealtime(1f);

十、方便使用的属性

  为变量添加一些属性可使它们在 Inspector 面板中更容易被使用。

  在变量前添加 Range 属性可将其限定在某个范围内使用滑块进行调节。

1     [Range(0f, 10f)]
2     public float speed = 1f;

  执行效果:

  两个变量声明之间加入 [Space] 可在 Inspector 中添加一个空行;添加 Header 可在 Inspector 面板中加入一段文字。

1     [Header("Player Settings")]
2     public float speed = 1f;
3     public float hp = 100;

  执行效果:

  在变量前加入 Tooltip,当鼠标悬停在 Inspector 面板中的变量上时,可显示关于此变量的说明。

1     [Tooltip("移动速度")]
2     public float speed = 1f;

  执行效果:

***| 以上内容仅为学习参考、学习笔记使用 |***

原文地址:https://www.cnblogs.com/ChenZiRong1999/p/13036045.html