FC2ブログ
    05 «1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.23.24.25.26.27.28.29.30.» 07

    ハルシオンシステムの気ままBlog

    株式会社ハルシオンシステムのメンバーが送る、UnityやらJavaやらの技術的話題から、自社開発のアプリの宣伝とかとかのブログです。ほんと気ままにいきたいと思います。更新日は毎週 月 木でっす!

     

    【ハルシオンブログ】Unity+LinqtoGameObjectで、"子供のオブジェクトを全部xxx"系の処理が簡単にできる! 

    こんにちは!坂内です!

    コロナ騒動になり飲みにいけなくなって早2か月?
    早くおいしいもの食べに行きたくてうずうずが止まらない今日この頃でございます。


    さてUnity+Linqのお話。

    オブジェクトの子供や孫を取得する際に、普段だとこんな感じでやっています。


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Blog20200601 : MonoBehaviour {

    public Transform itemParent;

    void Start() {
    DestroyItem();
    }

    void DestroyItem() {
    foreach (Transform itemTran in itemParent) {
    Destroy(itemTran.gameObject);
    }
    }
    }





    こんな感じでパッと消えます。

    LinqにもこのGameObjectを触る用のものがあるみたいです。

    【LINQ-to-GameObject-for-Unity】
    https://github.com/neuecc/LINQ-to-GameObject-for-Unity

    これを使うとこんな感じで書くことができます。


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Unity.Linq;

    public class Blog20200601 : MonoBehaviour {

    public GameObject itemParentObj;

    void Start() {
    DestroyItem();
    }

    void DestroyItem() {
    foreach (GameObject item in itemParentObj.Descendants()) {
    Destroy(item);
    }
    }
    }



    注意点としては、System.Linq: ではなく、Unity.Linq: になります。

    Descendantsを使いましたが、他にも以下のようなものがあるようです。

    Ancestors() : 親、親以上まで遡る
    Descendants() : 子供、子供以下まで下る
    Parent() : 親のみ
    Children() : 子供のみ

    といったものがあるようです。

    これを使うと、指定オブジェクトの子供以下で「タグが"test"のものを取得」も簡単に可能です。


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using Unity.Linq;
    using System.Linq;

    public class Blog20200601 : MonoBehaviour {

    public GameObject itemParentObj;

    void Start() {
    DestroyItem();
    }

    void DestroyItem() {
    foreach (GameObject item in itemParentObj.Descendants().Where(x => x.tag == "test")) {
    Destroy(item);
    }
    }
    }


    2、5、6の番号のオブジェクトにtestタグをつけています。



    こんな感じでいろいろ使えそうですね!


    では、あでゅ~ノシ

    Category: 開発日記(Unity)

    tb 0 : cm 0   

    コメント

    コメントの投稿

    Secret

    トラックバック

    トラックバックURL
    →http://halcyonsystemblog.jp/tb.php/705-f85605c3
    この記事にトラックバックする(FC2ブログユーザー)