LoginSignup
0
0

More than 1 year has passed since last update.

Cubeのインスタンス化を理解して実装する(Unity2019.4.13f)

Posted at

本記事の目的

インスタンス化を理解して、Unityで実際に動かすとこまで行う。
動作イメージ↓
ex10.gif

インスタンス化とは?

こちらを参考に↓
https://e-words.jp/w/%E3%82%A4%E3%83%B3%E3%82%B9%E3%82%BF%E3%83%B3%E3%82%B9%E5%8C%96.html#:~:text=%E3%82%A4%E3%83%B3%E3%82%B9%E3%82%BF%E3%83%B3%E3%82%B9%E5%8C%96%E3%81%A8%E3%81%AF%E3%80%81%E3%82%AA%E3%83%96%E3%82%B8%E3%82%A7%E3%82%AF%E3%83%88,%E3%82%A4%E3%83%B3%E3%82%B9%E3%82%BF%E3%83%B3%E3%82%B9%E3%80%8D%EF%BC%88instance%EF%BC%89%E3%81%A8%E3%81%84%E3%81%86%E3%80%82

なぜインスタンス化が必要なのか?

こちらがとってもわかりやすいです↓
https://qiita.com/kn2018/items/f99f62cabfd31667b055

実装例

ex09.gif

スクリプトは以下の通り

instance_cube.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class instance_cube : MonoBehaviour
{
    public float timeOut=1.0f;
    private float timeElapsed;
    public GameObject cube;

    void Update()
    {
        //timeElapsedに経過時間(Time.deltaTime)を加算 
        timeElapsed += Time.deltaTime;
        if (timeElapsed >= timeOut)
        {
            //InstantiateでGameObject生成 
            //Instantiate(複製するGameObject,位置,回転)の順番で記載 
            Instantiate(cube, new Vector3(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f)), Quaternion.identity);
            //timeElapsedを0.0fに戻す 
            timeElapsed = 0.0f;
        }
    }
}

親オブジェクトの下にインスタンス化する

ex13.gif

instance_cube_under_parent.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class instance_cube_under_parent : MonoBehaviour
{
    public float timeOut=1.0f;
    private float timeElapsed;
    public GameObject cube;
    public GameObject parent;

    void Update()
    {
        //timeElapsedに経過時間(Time.deltaTime)を加算 
        timeElapsed += Time.deltaTime;
        if (timeElapsed >= timeOut)
        {
            //InstantiateでGameObject生成 
            //Instantiate(複製するGameObject,位置,回転)の順番で記載 
            Instantiate(cube, new Vector3(Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f), Random.Range(-5.0f, 5.0f)), Quaternion.identity, parent.transform);
            //timeElapsedを0.0fに戻す 
            timeElapsed = 0.0f;
        }
    }
}

最後に

これでインスタンス化ができましたね。

0
0
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
0
0