Version: 2021.1

RequireComponent

class in UnityEngine

切换到手册

描述

RequireComponent 属性自动将所需的组件添加为依赖项。

向 GameObject 添加使用 RequireComponent 的脚本时,会自动将需要的组件添加到 GameObject 中。 这对避免设置错误非常有用。 例如,脚本可能要求始终向同一 GameObject 添加 Rigidbody。 使用 RequireComponent 可自动完成此工作,也就不会出现设置错误。 请注意,RequireComponent 只在组件添加到 GameObject 中时检查是否缺少依赖项。GameObject 缺少新依赖项的现有组件实例将不会自动添加这些依赖项。

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需要一个组件。
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961