オブジェクトに付けられているコンポーネントを取得する

もくじ
https://tera1707.com/entry/2022/02/06/144447

やりたいこと

オブジェクトにつけられているComponentを取る。

付けられてるコンポーネントとは、下図に出てる、「RigidBody」「AudioSource」などのヤツら。

これらが取れると、C#スクリプトから、

とかができる。

やりかた

まず、コンポーネントの型のフィールドを定義する。

public class PlayerControllerX : MonoBehaviour
{
    private Rigidbody playerRb;
    private AudioSource playerAudio;

次に、GetComponent<コンポーネントの型>()で、コンポーネントを取得する。

Start()で、一回取っておけばとりあえずOK。

void Start()
{
    playerAudio = GetComponent<AudioSource>();
    playerRb = GetComponent<Rigidbody>();

で、使いたいところで使う。

playerRb.AddForce(Vector3.up * 5, ForceMode.Impulse);