今天来介绍一个Unity中比较实用的类RequireComponent。RequireComponent的作用是,当我们把一个Script绑定到GameObject上时会同时把需要依赖的脚本也一起绑定上去。与Image脚本一样,当我们在一个GameObject上绑定Image时会自动绑定CanvasRender。
这样做的好处有,1.可以减少操作,当绑定需要的脚本的时候其所依赖的脚本也一起绑定,很方便。2.可以避免因遗漏绑定其他脚本而出错。下面来看一下RequireComponent的具体使用。
using UnityEngine;
// PlayerScript requires the GameObject to have a Rigidbody component
[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour
{
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
rb.AddForce(Vector3.up);
}
}
我们只需要在类声明处上面增加 [RequireComponent(typeof(Rigidbody))] 这样一行就可以了,上面的例子是依赖绑定一个Rigidbody。RequireComponent指定的参数为Type类型,最多可以传入3个参数。RequireComponent的使用非常的简单,也非常的实用。
下面是RequireComponent的官方文档,需要的小伙伴可以自行查阅。
https://docs.unity3d.com/ScriptReference/RequireComponent.html
https://docs.unity3d.com/ScriptReference/RequireComponent-ctor.html