このブログを検索

2019年12月15日日曜日

【C#】Unity - 2Dオブジェクト複製(Prefab)

【C#】Unity - 2Dオブジェクト複製(Prefab)
(2019年12月15日)


■使用ソフト
・Unity Hub 2.1.3
・Unity 2019.2.11f1
・Visual Studio Community 2019


■言語
・C#


■手順
1.Unity Hub起動→プロジェクト→新規作成

2.2Dを選択→プロジェクト名、保存先を設定→作成

3.画像を用意してAssetsへドラッグ&ドロップ
start.png
サイズ:128×128ピクセル


4.画像をヒエラルキーへドラッグ&ドロップ

5.Assetsで右クリック→作成→C#スクリプト

6.作成したC#スクリプトをダブルクリックしてVisual Studioを起動

7.コードを以下のとおり変更して保存する

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

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

    // Update is called once per frame
    void Update()
    {
        transform.Translate(0.1f, 0, 0);//右に移動
        if(transform.position.x > 5.0f)
        {
            Destroy(gameObject);//位置Xが5を超えたら消す
        }
    }
}

8.C#スクリプトをヒエラルキーのstartへドラッグ&ドロップ

9.ヒエラルキーのstartをAssetsへドラッグ&ドロップ
 Prefabが作成される

10.ヒエラルキーのstartは、右クリック→削除で削除しておく

11.Assetsで右クリック→作成→C#スクリプト

13.作成したC#スクリプトをダブルクリックしてVisual Studioを起動

14.コードを以下のとおり変更して保存する

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

public class NewBehaviourScript1 : MonoBehaviour
{
    public GameObject startPrefab;//publicを必ずつける
    float fTime;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        this.fTime += Time.deltaTime;//1フレームの時間を加算する
        if(this.fTime > 0.3f)//0.3秒ごとの処理
        {
            this.fTime = 0;
            GameObject copyStart = Instantiate(startPrefab) as GameObject;//新しいオブジェクトを作る
            int iY = Random.Range(-3, 4);//-3~3のランダムな整数を作る(-3~4ではない)
            copyStart.transform.position = new Vector3(-5.0f, iY, 0);//新しいオブジェクトの位置を設定
        }
    }
}

15.ヒエラルキーの作成→空のオブジェクトを作成

16.2つ目に作成したC#スクリプトをヒエラルキーのGameObjectへドラッグ&ドロップ

17.ヒエラルキーのGameObjectを選択してPrefabをインスペクターのStart Prefabへドラッグ&ドロップ


4.実行結果
0.3秒ごとに矢印が左端(高さランダム)に生成され、右に動いて右端で消える


■参考文献
Unityの教科書 Unity2018完全対応版

0 件のコメント:

コメントを投稿