- Home /
How do I delete the elements in array?
Hi, I want to delete the specific element in array. I'm trying to spawn the objects at random locations. I'm storing some random positions in array to randomly spawn the objects. So I want to delete the spawned position so that object won't spawn again at that position. How do I do this? and I'm using javascript.
Answer by fafase · Jan 15, 2013 at 10:03 AM
You should use a list instead. Array could do but you would have to keep track of indexes or in the end you would be doing manually what a list does automatically.
List<Vector3> positions = new List<Vector3>();
positions.Add(new Vector3(0,0,0));
Do this for all positions and then you can use like below:
int ind = new Random(0, positions.Count);
Instantiate(prefab, positions[ind],Quaternion.identity);
positions.RemoveAt(ind);
Your list will remove the value at ind and shrink automatically. The useless data will collected on the next garbage collection. positions.Count will also decrease to amke sure you do not get an out of bound index.
He mentions Javascript in the tags -> so in JS that is:
var positions = new List.<Vector3>();
positions.Add(Vector3(0,0,0)); //Etcetera
var ind = Random.Range(0, positions.Count);
Instantiate(prefab, positions[ind], Quaternion.identity);
positions.RemoveAt(ind);
You shouldn't have to but you could stick an
import System.Collections.Generic;
at the top of your file.
Your answer
Follow this Question
Related Questions
Problem removing items from array 2 Answers
List problem? 2 Answers
Distance error: Cannot cast from source type to destination 0 Answers
Find colliders after collision? 2 Answers
Change rigidbody values on mutliple objects (ARRAY) 1 Answer