LoginSignup
0
0

More than 3 years have passed since last update.

【Unity】gameObjectのgameObject

Posted at

スクリプトからゲームオブジェクトを取得する

gameObjectからアタッチしているゲームオブジェクトのインスタンスを取得することが可能(リファレンス)。
MonoBehaviourの継承が必要だがそもそもアタッチしている時点で継承する必要あり。

例えばCubeオブジェクトにスクリプトをアタッチしてデバッグログでgameObjectを出力した場合。

SampleObject.cs
public class SampleObject : MonoBehaviour {

    private void Start () {
        Debug.Log(gameObject);
    }
}
Console
Cube (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)

こんなこと誰でも知ってるよね

gameObjectのgameObject

gameObjectGameObjectだが、GameObjectgameObjectを持っている(下記参照)。

GameObject.cs
namespace UnityEngine
{
    [ExcludeFromPreset]
    [NativeHeaderAttribute("Runtime/Export/GameObject.bindings.h")]
    [UsedByNativeCodeAttribute]
    public sealed class GameObject : Object
    {
        ...
        //
        // Summary:
        //     Scene that the GameObject is part of.
        public Scene scene { get; }
        public GameObject gameObject { get; }
        ...
    }
}

つまりgameObject.gameObjectみたいな書き方も可能。インスタンスも同じである。

SampleObject.cs
private void Start () {
    Debug.Log(gameObject.gameObject);
    Debug.Log(gameObject == gameObject.gameObject);
}
Console
Cube (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)

True
UnityEngine.Debug:Log(Object)

その気になればgameObject.gameObject.gameObjectなんて書くことも可能、たくさん繋げられる。

SampleObject.cs
private void Start () {
    Debug.Log(gameObject.gameObject.gameObject);
    Debug.Log(gameObject == gameObject.gameObject.gameObject);
}
Console
Cube (UnityEngine.GameObject)
UnityEngine.Debug:Log(Object)

True
UnityEngine.Debug:Log(Object)

何故こういう動きになるのか気になって調べてみたのですがあまり有力な情報は得られず。
何か知っている人がいたらコメント等で教えて下さい。

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