[Unityのヒント] RequireComponent



Requirecomponent



今日は、Unityでより実用的なクラスRequireComponentを紹介します。 RequireComponentの役割は、スクリプトをGameObjectにバインドするときに、依存する必要のあるスクリプトもバインドすることです。 Imageスクリプトと同様に、GameObjectでImageをバインドすると、CanvasRenderが自動的にバインドされます。

これの利点は次のとおりです:1。それは操作を減らすことができます。必要なスクリプトをバインドするときに、それらが依存するスクリプトも一緒にバインドされます。これは非常に便利です。 2.他のスクリプトが欠落していることによるエラーを回避できます。 RequireComponentの特定の使用法を見てみましょう。



using UnityEngine // PlayerScript requires the GameObject to have a Rigidbody component [RequireComponent(typeof(Rigidbody))] public class PlayerScript : MonoBehaviour { Rigidbody rb void Start() { rb = GetComponent() } void FixedUpdate() { rb.AddForce(Vector3.up) } }

[RequireComponent(typeof(Rigidbody))]をクラス宣言に追加するだけで済みます。上記の例は、リジッドボディのバインドに依存しています。 RequireComponentで指定されたパラメーターはType型であり、最大3つのパラメーターを渡すことができます。 RequireComponentの使用は非常に簡単で、非常に実用的です。

以下は、RequireComponentの公式ドキュメントです。これは、必要な小規模なパートナーが表示できます。



https://docs.unity3d.com/ScriptReference/RequireComponent.html

https://docs.unity3d.com/ScriptReference/RequireComponent-ctor.html