1.[RequireComponent(typeof(...))]
当某个脚本必须依赖其他脚本或者组件共同使用时,为了避免人为添加过程的操作失误,可以在代码中使用RequireComponent,它的作用就是添加该脚本时,会自动将所依赖的各个组件添加至gameobject上,避免人为操作的失误。
具体使用方法如下:
1)新建一个GameObject对象,同时新建C#脚本,例如test1.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对象,会有如下提示