Using Destroying Objects in a List of Gameobjects - argument out of range.
Hi there!
I'm creating a puzzle game which drops pieces. I want the user to be able to change the pieces, therefore this code allows the spawning of new pieces while destroying the old ones. I am referencing a list, adding to the list as new pieces are spawned. I assumed I could just destroy the highest in the index. This works once, but then stops with a "argument out of range exception".
new to coding!
using UnityEngine; using System.Collections; using System.Collections.Generic;
public class game : MonoBehaviour {
private int nextPiece;
private int currentPiece = -1;
List<GameObject> spawnedPieces = new List<GameObject>();
// Use this for initialization
void Start () {
SpawnNextPiece ();
}
// Update is called once per frame
void Update () {
//Switch Pieces on M
if (Input.GetKeyUp(KeyCode.M))
{
DestroyCurrentPiece ();
SpawnNextPiece ();
}
}
public void DestroyCurrentPiece () {
Debug.Log ("Current Piece : " + currentPiece);
GameObject.Destroy (spawnedPieces[currentPiece]);
spawnedPieces.RemoveAt (currentPiece);
}
public void SpawnNextPiece () {
GameObject nextPiece = (GameObject)Instantiate (Resources.Load (GetNextPiece(), typeof(GameObject)), new Vector3 (0.5f, 7.5f, 0.25f), Quaternion.identity);
spawnedPieces.Add(GameObject.FindGameObjectWithTag("pieces"));
}
string GetNextPiece () {
currentPiece += 1;
nextPiece += 1;
if (nextPiece >= 3) {
nextPiece = 1;
}
string nextPieceName = "Pieces/002";
switch (nextPiece) {
case 1:
nextPieceName = "Pieces/002";
break;
case 2:
nextPieceName = "Pieces/003";
break;
}
return nextPieceName;
}
}
Your answer
Follow this Question
Related Questions
Random Choose a List if it has a count more than 0 0 Answers
Adding new spawned objects to a list? 0 Answers
Unity lists not working while using collection generic 3 Answers
Can someone help me make a simple jump script? 6 Answers
pc linux mac standalone 0 Answers