Version: 2022.3
言語: 日本語

RequireComponent

class in UnityEngine

マニュアルに切り替える

説明

RequireComponent 属性は、必要なコンポーネントを依存関係として自動的に加えます。

When you add a script which uses RequireComponent to a GameObject, the required component is automatically added to the GameObject. This is useful to avoid setup errors. For example a script might require that a Rigidbody is always added to the same GameObject. When you use RequireComponent, this is done automatically, so you are unlikely to get the setup wrong.

Note: RequireComponent only checks for missing dependencies when GameObject.AddComponent is called. This happens both in the Editor, or at runtime. Unity does not automatically add any missing dependences to the components with GameObjects that lack the new dependencies.

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); } }

コンストラクタ

RequireComponent1 つのコンポーネントを必要とします