Unityで、Hierarychy上のGameObject操作を簡単に行えるAssetとして、LINQ to GameObjectというものがあります。これを使うと、ツリーの中から特定の条件に一致するGameObjectやComponentを検索する処理を簡単に書くことができます。
今回は、LINQ to GameObjectの基本的な使い方を紹介します。
まずは動作確認をかねて、基本的な使い方の説明です。
下記のコードでHierarychy上にある自陣の子孫に当たる全GameObjectを取得します。
LINQ to GameObjectを使うためには、”using Unity.Linq;”が必要なので、注意が必要です。
using UnityEngine; using System.Collections; using Unity.Linq; public class SampleScript : MonoBehaviour { // Use this for initialization void Start () { // 自分の子に存在するすべてのGameObjectを列挙する foreach ( GameObject obj in this.gameObject.Descendants() ) { Debug.Log( obj.name ); } } } |
Descendants()は、自分の子孫にあたるGameObjectを検索しますが、下記のメソッド達があります。
Ancestors(); // 祖先(親、親の親...) Descendants(); // 子孫(子、孫...) Parent(); // 直接の親(親の親は含まない) Children(); // 直接の子供(孫要素は含まない) BeforeSelf(); // 兄弟要素のうち、自分より上にあるもの AfterSelf(); // 兄弟要素のうち、自分より下にあるもの |
次は、uGUIのButtonオブジェクトだけを取得してみます。
GameObjectが持つ、特定のComponentだけを抽出するには、OfComponent()メソッドを使用します。
using UnityEngine; using System.Collections; using Unity.Linq; using UnityEngine.UI; public class SampleScript : MonoBehaviour { void Start () { foreach ( Button button in this.gameObject.Descendants().OfComponent<Button>() ) { Debug.Log( button.name ); } } } |
LINQのWhere()なども使用できるので、以下のような感じで、特定の名前を持つGameObjectだけをさらに絞り込むことも可能です。LINQのWhere()は少し読みづらくて抵抗がある…という場合は、普通にforeachの中でif文を書いて絞り込んでしまってもOKです。
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using Unity.Linq; using UnityEngine.UI; public class SampleScript : MonoBehaviour { void Start () { foreach ( GameObject enemy in this.gameObject.Descendants().Where( x => (x.name=="enemy") ) ) { Debug.Log( enemy.name ); } } } |
LINQ to GameObjectでは、他にDestroy()拡張メソッドも用意してくれているので、
以下のように、条件に一致するオブジェクトを一気に消すことも可能です
this.gameObject.Descendants() .Where( x => (x.name=="effect") ) .Destroy(); |
関連記事
コメントを残す