オブジェクト配下にInstantiateでオブジェクトを生成する【Unity】

今回はUnityでinstantiateで生成したオブジェクトを指定した親オブジェクトに割り当てる方法のメモです。

はじめに

Unityのバージョンは2021.3.3f1です。

以前、作成したシューティングゲームを元に作成していきます。InstantiateがあればなんでもOK。

シューティングゲームでは、弾を打ち出すと弾のプレハブがどんどん生成されます。

弾を打ち出しているスクリプトは下記。

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

public class PlayerAttack : MonoBehaviour
{
    public GameObject prefabBullet;
    public Transform bulletPoint;

    public void Attack()
    {
        Instantiate(prefabBullet, bulletPoint.position, bulletPoint.rotation);
    }
}

これを下記の様にスクリプトを変更。

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

public class PlayerAttack : MonoBehaviour
{
    public GameObject prefabBullet;
    public Transform bulletPoint;

    [SerializeField] GameObject _parentGameObject;
    public void Attack()
    {
        Instantiate(prefabBullet, bulletPoint.position, bulletPoint.rotation, _parentGameObject.transform);
    }
}

SerializeField変数に、親となるオブジェクトを指定。Instantiateのパラメータで指定したオブジェクトの配下に生成します。

参考は下記の公式リファレンス。

下記の様に親オブジェクトを取得する方法もあるけど、Inspectorで指定するのが自然かも。

GameObject.Find("Bullets");
GameObject.FindGameObjectWithTag("Bullets");

スクリプトをアタッチしているオブジェクトの配下に生成する場合は、下記の様な感じ。

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

public class PlayerAttack : MonoBehaviour
{
    public GameObject prefabBullet;
    public Transform bulletPoint;

    public void Attack()
    {
        Instantiate(prefabBullet, bulletPoint.position, bulletPoint.rotation, transform);
    }
}
タイトルとURLをコピーしました