RequireComponent的使用

来源:互联网 发布:php打印直角三角形 编辑:程序博客网 时间:2024/06/06 04:47
当某个脚本必须依赖其他脚本或者组件共同使用时,为了避免人为添加过程的操作失误,可以在代码中使用RequireComponent,它的作用就是添加该脚本时,会自动将所依赖的各个组件添加至gameobject上,避免人为操作的失误。
具体使用方法如下:

1、新建一个GameObject对象,同时新建两个C#脚本,例如图中的test1.cs与test2.cs
2、编辑test1.cs脚本,将编辑好后的test1拖至GameObject对象上
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Rigidbody),typeof(test2))]
public class test1 : MonoBehaviour {
}
或:
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(test2))]
public class test1 : MonoBehaviour {
}
(也可以分开写,效果一样。同时可根据实际项目需求,修改[RequireComponent(typeof(Rigidbody))] 中的组件类型)

3、此时若手动删除Rigidbody对象,会有如下提示

因此,RequireComponent的使用可以很好的避免项目中因为相互依赖的组件缺失而导致不必要的错误。


阅读全文
0 0
原创粉丝点击