本日は Unity の小ネタ枠です。
UnityでRectTransform配下での子オブジェクトの生成/破棄を行う方法を試します。
子オブジェクトの生成と破棄
子オブジェクトの生成は通常の生成と同様に Instantiate 関数に生成するオブジェクトと生成箇所の RectTransform を指定して行います。
Transform ContentRoot;
// --- 略 ---
Instantiate(TextPrefab, ContentRoot);
子オブジェクトの破棄は RectTransform では子オブジェクトへの Cast や Destroy の直接指定ができないため、以下のように Destroy 関数を実行します。
Transform ContentRoot; // --- 略 --- for(int index = 0; index < ContentRoot.childCount; index++) { // RectTransform の指定だと削除が失敗するので gameObject を指定する Destroy(ContentRoot.GetChild(index).gameObject); }
以下のような通常の Transform に対して実行する構文ではエラーが発生します。
Transform ContentRoot; // --- 略 --- foreach(GameObject obj in ContentRoot) { Destroy(obj); }
サンプルシーンとスクリプト
以下のサンプルシーンとオブジェクト生成/破棄を行うスクリプトを作成しました。
・InstantiateDestroyTest.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class InstantiateDestroyTest : MonoBehaviour { /// <summary> /// 生成するプレハブ /// </summary> public GameObject SpawnPrefab; /// <summary> /// 生成箇所のトランスフォーム /// </summary> public Transform ContentRoot; [ContextMenu("Make")] public void MakeContent() { Instantiate(SpawnPrefab, ContentRoot); } [ContextMenu("Delete")] public void DelateContent() { for(int index = 0; index < ContentRoot.childCount; index++) { // RectTransform の指定だと削除が失敗するので gameObject を指定する Destroy(ContentRoot.GetChild(index).gameObject); } } }
動作確認
ContextMenu から[Make]を実行すると RectTransform 配下に子オブジェクトが生成されます。
ContextMenu から[Delete]を実行すると RectTransform 配下の子オブジェクトが全て破棄されます。