LoginSignup
0
0

More than 1 year has passed since last update.

UnityのGetcomponentで親や子のコンポーネントを取得する方法

Posted at

Unityでゲームを作る時、オブジェクトの数が多いときや
自動生成されるゲームオブジェクトだと、コードからコンポーネントを取得したい時が多いですよね?

今回はそんなコードから親や子オブジェクトからコンポーネントを
取得したい時の対処方法について紹介していきます!

UnityのGetComponentの効果

GetComponentはゲームオブジェクトに
アタッチされているコンポーネントを
取得できるコードになっています。

例えば下記オブジェクトのTransFormコンポーネントを取得したい場合は

  1. スクリプト作成
  2. Squareオブジェクトに作成したスクリプトをアタッチ
  3. コード記述

上記で可能になっています。
image.png

サンプルコード
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private Transform square;

    void Start()
    {
        square = GetComponent<Transform>();
    }

}

親オブジェクトから子オブジェクトのコンポーネントを取得するには

この機能を使えば親のオブジェクトからも
コンポーネントを取得することが可能になっています。
image.png

例えばSquare_ChildrenオブジェクトのTransFormコンポーネントを
Squareから取得したい場合は

  1. スクリプト作成
  2. Square_Childrenオブジェクトに作成したスクリプトをアタッチ
  3. コード記述

上記で可能になっています。

サンプルコード
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private Transform square;

    void Start()
    {
        square = GetComponentInChildren<Transform>();
    }
}

子オブジェクトから親オブジェクトのコンポーネントを取得するには

さらには子オブジェクトから親オブジェクトのコンポーネントを
取得することも可能になっています。

image.png

例えばSquareオブジェクトのTransFormコンポーネントを
Square_Childrenから取得したい場合は

  1. スクリプト作成
  2. Squareオブジェクトに作成したスクリプトをアタッチ
  3. コード記述
サンプルコード
Test.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Square_Children : MonoBehaviour
{

    private Transform square;

    void Start()
    {
        square = GetComponentInParent<Transform>();//一番上の親についているコンポーネントを取得する
    }
}

YouTubeチャンネル

ゲーム雑学や、具体的なゲーム開発方法まで紹介しているチャンネルを運営しています!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0