Q&A
Unityでのエラーについて。
以下のコードを実行するとオブジェクトを作成するところで以下のようなエラーがでてしまいます。
Index was out of range. Must be non-negative and less than the size of the collection.
以下でやっていることは、
・オブジェクト(note)が入るリストを作成
・1秒ごとに新しいオブジェクトを複製し、連番で名前をつける(note0, note1, …)
・フレーム毎にオブジェクトが移動する(Z軸方向)
・オブジェクトのz軸が0以下になったら、オブジェクトを見えなくする
(本当は削除したいがDestroyにするとエラーがでる)
音ゲーの音符がランダムに生成されて、飛んできて、
z軸が0のところまできらた消えるというのをイメージして作っているのですが、
Unityを触って数日のため思い通りに動きません><
作り変えてしまっても構いませんので、
もっと効率のいいやり方を教えてください…
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class NoteManeger : MonoBehaviour 6{ 7 8 public float noteSpeed = 0.5f; 9 public float initPosZ = -3.0f; 10 private List<GameObject> noteList; 11 public GameObject prefab; 12 public GameObject star; 13 // 作成した音符オブジェクトの累計数 14 private int noteConut = 0; 15 //経過時間 16 private float timeElapsed; 17 //削除したオブジェクトの累計数 18 private int destroyCount = 0; 19 20void Start() 21 { 22 noteList = new List<GameObject>(); 23 } 24 25void Update() 26 { 27 createNote(1.0f); 28 moveNote(); 29 removeNote(); 30 } 31 32void createNote(float time) 33 { 34 timeElapsed += Time.deltaTime; 35 if (timeElapsed >= time) 36 { 37 38 noteList.Add(Instantiate(prefab, new Vector3 (Random.Range (-1.5f, 1.5f), Random.Range(0.0f, 2.0f), initPosZ), Quaternion.identity) as GameObject); 39 Debug.Log(noteConut); 40 // リストへ追加したオブジェクトに連番をつける 例:note0, note1, ... 41 noteList[noteConut].name = "note" + noteConut; 42 timeElapsed = 0.0f; 43 // 累計音符数を1増やす 44 noteConut += 1; 45 } 46 } 47 48 49 void moveNote() 50 { 51 for(int i = destroyCount; i < noteList.Count; i++) 52 { 53 if(noteList[i].activeSelf == true) 54 { 55 Vector3 pos = noteList[i].transform.position; 56 noteList[i].transform.position = new Vector3(pos.x, pos.y, pos.z + noteSpeed); 57 } 58 } 59 } 60 61 void removeNote() 62 { 63 for(int i = destroyCount; i < noteList.Count; i++) 64 { 65 if(noteList[i].activeSelf == true) 66 { 67 Vector3 pos = noteList[i].transform.position; 68 if(pos.z > 0.0f) 69 { 70 // オブジェクトの削除 71 noteList[i].SetActive(false); 72 // リスト内も削除 73 noteList.RemoveAt(i); 74 destroyCount++; 75 } 76 } 77 } 78 } 79}
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2019/03/29 13:28
2019/03/29 13:37
2019/03/29 13:48
2019/03/29 13:55
2019/03/29 14:19
2019/03/29 14:22
2019/03/29 21:39