7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ゲームオブジェクトの参照

Last updated at Posted at 2017-10-04
Hierarchy
RootCube
	└ MyCube
		└ ChildCube

前提:MyCubeにスクリプトをアタッチしている状態

インスペクタからアタッチする

public GameObject TargetCube;

SerializeField
https://docs.unity3d.com/jp/540/ScriptReference/SerializeField.html

[SerializeField] GameObject TargetCube;

シーンの中からざっくり探す

GameObject.Find
https://docs.unity3d.com/jp/540/ScriptReference/GameObject.Find.html

GameObject TargetCube;

void Start () {
    TargetCube = GameObject.Find("MyCube"); // ユニークな名前
}

シーンの中からタグで探す

GameObject.FindWithTag
https://docs.unity3d.com/jp/540/ScriptReference/GameObject.FindWithTag.html

GameObject TargetCube;

void Start () {
    TargetCube = GameObject.FindWithTag("cube");
}

シーンの中からタグで探す(複数)

GameObject.FindGameObjectsWithTag
https://docs.unity3d.com/ja/540/ScriptReference/GameObject.FindGameObjectsWithTag.html

GameObject[] respawns;

void Start () {
    respawns = GameObject.FindGameObjectsWithTag("Respawn");
}

子要素を探す

Transform.Find
https://docs.unity3d.com/jp/540/ScriptReference/Transform.Find.html

GameObject TargetCube;

void Start () {
    // Transform情報を返すので、ChildCubeが必要ならgameObjectをつける
    TargetCube = transform.Find("ChildCube").gameObject;
}

Transform
https://docs.unity3d.com/jp/540/ScriptReference/Transform.html

非アクティブな要素を取得することもできるので重要
UnityでアクティブでないGameObjectを取得する

子要素から親要素を探す

変数 意味
parent Transform の親
root 階層の一番上の Transform

parent

GameObject TargetCube;

void Start () {
    TargetCube = GameObject.Find("ChildCube");
}
void Update () {
    TargetCube.transform.parent.Rotate(0, Time.deltaTime * 50, 0);
}

root(中央)は動かず、MyCubeを(一番下)中心に回転する

parent.gif

root

GameObject TargetCube;

void Start () {
    TargetCube = GameObject.Find("ChildCube");
}
void Update () {
    TargetCube.transform.root.Rotate(0, Time.deltaTime * 50, 0);
}

rootごと回しているので、全てのオブジェクトが回転する

root.gif

7
2
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
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?