Unityでシーンが作成されてからn秒後にObjectを生成したいのですが、
以下のコードでは実行後に全体の処理が3秒とまって作成されてしまいうまくいきませんでした。(全体の処理を止めずにn秒後に生成したい)
createNoteが呼ばれたときに、引数で指定した秒数後にオブジェクトを作成したいです。
メインの処理を中断させないで、指定時間後に作成したいです。
C#
1void createNote(float time) 2 { 3 nowTime += Time.deltaTime; 4 while(nowTime <= time) 5 { 6 nowTime += Time.deltaTime; 7 Debug.Log(nowTime); 8 Debug.Log(time); 9 if (nowTime >= time) 10 { 11 オブジェクト生成 12 } 13 } 14 }
コード全体
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class NoteManeger : MonoBehaviour 6{ 7 public float noteSpeed = 0.3f; 8 public float initPosZ = -1.0f; 9 // GameObject型のみが入るnoteListを宣言 10 private List<GameObject> noteList; 11 // Unity上からプレハブを割り当てておく 12 public GameObject prefab; 13 public GameObject star; 14 // 作成したオブジェクトの累計数 15 private int noteConut = 0; 16 //経過時間 17 private float nowTime = 0.0f; 18 private int destroyCount = 0; 19 20 21 void Start() 22 { 23 // 1秒間に30フレーム更新 24 Application.targetFrameRate = 30; 25 noteList = new List<GameObject>(); 26 createNote(3.0f); 27 } 28 29 // 1フレームあたりの処理 30 void Update() 31 { 32 //n秒後にオブジェクトが生成される 33 createNote(3.0f); 34 moveNote(); 35 removeNote(); 36 } 37 38 void createNote(float time) 39 { 40 nowTime += Time.deltaTime; 41 while(nowTime <= time) 42 { 43 nowTime += Time.deltaTime; 44 Debug.Log(nowTime); 45 Debug.Log(time); 46 if (nowTime >= time) 47 { 48 noteList.Add(Instantiate(prefab, new Vector3 (Random.Range (-1.5f, 1.5f), Random.Range(0.0f, 2.0f), initPosZ), Quaternion.identity) as GameObject); 49 // リストへ追加したオブジェクトに連番をつける 例:note0, note1, ... 50 noteList[noteConut].name = "note" + noteConut; 51 //nowTime = 0.0f; 52 // 累計数を1増やす 53 noteConut += 1; 54 break; 55 } 56 } 57 } 58 59 60 // オブジェクトを移動させる関数 61 void moveNote() 62 { 63 for(int i = destroyCount; i < noteList.Count; i++) 64 { 65 if(noteList[i].activeSelf == true) 66 { 67 // オブジェクト自身の座標を取得 68 Vector3 pos = noteList[i].transform.position; 69 // オブジェクトの座標を変更 70 noteList[i].transform.position = new Vector3(pos.x, pos.y, pos.z + noteSpeed); 71 } 72 } 73 } 74 75 // オブジェクトを削除する関数 76 void removeNote() 77 { 78 for(int i = destroyCount; i < noteList.Count; i++) 79 { 80 if(noteList[i].activeSelf == true) 81 { 82 // オブジェクト自身の座標を取得 83 Vector3 pos = noteList[i].transform.position; 84 // オブジェクトの座標が-2より小さくなったら、そのオブジェクトを削除 85 if(pos.z > -2.0f) 86 { 87 // オブジェクトの削除 88 Destroy (noteList[i]); 89 destroyCount++; 90 } 91 } 92 } 93 } 94 95} 96
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/03/30 02:58
2019/03/30 04:09
2019/03/30 04:47
2019/03/30 06:00
2019/03/30 06:34
2019/03/30 06:50
2019/03/30 06:53