3
5

More than 3 years have passed since last update.

Unityでオブジェクトを動的生成する

Posted at

スクリプトによってオブジェクトを自動生成させる。

新しくspriteを追加して,Assetに適当な画像を追加し,その画像をNew SpriteのSpriteにドラッグ&ドロップする。
douteki_imageset.png

Assetsにフォルダを加える。名前は「Resources」にする。こうしないと動かない。
理由としては内部的にResourcesフォルダの中のファイルを取得できる「Resources関数」を使用するかららしい。
douteki_createfolder.png

プレハブ(Prefab)を作成する。
New SpriteをResourcesフォルダにドラッグ&ドロップする。
douteki_createprefab.png

フォルダ内にNew Spriteのプレハブが作られる。
douteki_checkprefab.png

Hierarchyを右クリックしてCreateEmptyする。
douteki_createempty.png

GameObjectに新しくスクリプトをAdd Componentする。
douteki_addcomponent.png

スクリプト名はなんでもいいが、とりあえずAddObjectにしてCreate and Addを押す。
douteki_rename.png

スクリプトファイルをダブルクリックするとvisual studioが開く。
douteki_scriptdoubleclick.png

スクリプトの中身をアタッチする。

元のこれを

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

public class CreateObject : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

Start()関数をいじってこのよう変更する

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

public class AddObject : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        // ResourcesフォルダにあるNew SpriteプレハブをGameObject型で取得
        GameObject obj = (GameObject)Resources.Load("New Sprite");
        // New Spriteプレハブを元に、インスタンスを生成、
        Instantiate(obj, new Vector3(0.0f, 2.0f, 0.0f), Quaternion.identity);
    }

    // Update is called once per frame
    void Update()
    {

    }
}

ctrl + s で保存して、実行すると
douteki_zikkou.png

指定した位置(今回は中心からちょっと上)にオブジェクトが出現する。
Hierarchyにもクローンが生成される(増えてくると番号が割り振られる?)。
douteki_result.png

参考:https://www.sejuku.net/blog/54672

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5