[RequireComponent(typeof(....))]

当某个脚本必须依赖其他脚本或者组件共同使用时,为了避免人为添加过程的操作失误,可以在代码中使用RequireComponent,它的作用就是添加该脚本时,会自动将所依赖的各个组件添加至gameobject上,避免人为操作的失误。

例:

[RequireComponent(typeof(Image))]
public class Person : MonoBehaviour
{
    
    
}

为物体挂载该脚本时Image组件将自动添加在物体的Inspector面板

猜你喜欢

转载自blog.csdn.net/weixin_45023328/article/details/125788005