今回は、シーン上にあるものを取得する方法を二つ記述していきます。
セットで読んでおくと良い記事↓
準備
今回は、このCapsuleとCubeを使っていきます。

それぞれタグを設定します。


スクリプトをアタッチするための空のオブジェクトを使います。名前をObjectFinderとします。

オブジェクトの名前で取得する
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindObject : MonoBehaviour
{
void Start()
{
GameObject Capsule = GameObject.Find("オブジェクトの名前");
Debug.Log(Capsule);
}
}
これを、ObjectFinderにアタッチして実行するとConsoleにオブジェクトの名前が出てきます。

取得していることがわかりますね!
スクリプトのポイント
このスクリプトのポイントは、GameObject.Find()関数です。
これを使えばゲームオブジェクトを取得することができます。
あとは、GameObject.Find(“オブジェクトの名前”)というように引数の中に取得したいオブジェクトの名前を入れれば機能します。
オブジェクトのタグで取得する
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindObject : MonoBehaviour
{
void Start()
{
GameObject capsule = GameObject.FindGameObjectWithTag("タグの名前");
Debug.Log(capsule);
}
}
これで、実行をすると

さっきと同じ結果ですが、タグで取得をしています。
スクリプトのポイント
このスクリプトのポイントは、GameObject.FindGameObjectWithTag()関数ですね。
これは、オブジェクトのタグでゲームオブジェクトを取得する関数です。
GameObject.FindGameObjectWithTag(“タグの名前”)というように引数の中に取得したいオブジェクトのタグを入れれば機能します。
同じタグのオブジェクトすべてを取得する
先ほどのタグの取得の方法では一つしかオブジェクトを取得することができません。
次は、同じタグのもの全部を取得できるようにしましょう。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FindObject : MonoBehaviour
{
void Start()
{
GameObject[] capsule = GameObject.FindGameObjectsWithTag("タグの名前");
foreach(GameObject Capsule in capsule)
{
//やりたい処理
}
}
}
僕の場合は、やりたい処理を「2秒後にCapsuleだけが消える」ようにします。
実行をしてみましょう。

成功ですね!
スクリプトのポイント
このスクリプトのポイントは、GameObject.FindGameObjectsWithTag()関数です。
これは、複数のオブジェクトのタグでゲームオブジェクトを取得する関数です。
返り値はGameObject[] capsuleというように配列ですので注意です。
GameObject.FindGameObjectsWithTag(“タグの名前”)というように引数の中に取得したいオブジェクトのタグを入れます。
そして、foreachで配列の中身を取得して処理を書けば完了です。
まとめ
いかがでしたでしょうか?
このスクリプトは意外と使うと便利ですので是非使ってみてください!
コメント