- Home /
Removing objects from array in reverse order
I have a selection mechanic that will select objects underneath a drag gesture. I'm trying to deselect the objects when retracing the gesture backwards... the code bellow works for deselecting objects when going over them again, but i want to limit it to the order the objects are in the array. Essentially so objects can only be deselected in the reverse order they were selected in, including the last. if that makes sense.
else if(hit.transform.GetComponent("ObjectSelected").isSelected == true && dragging)
{
for(var zz : int = selected.length-1; zz >= 0; zz--){
zz -= 1;
if(selected[zz] == hit.transform)
{
selected.RemoveAt(zz);
hit.transform.GetComponent("ObjectSelected").Selected(false);
//Debug.Log("Selected object index length= " + selected.length);
//selected.RemoveAt(selected.length-1);
//selected[selected.length-1].transform.GetComponent("ObjectSelected").Selected(false);
break;
}
}
Answer by Tasarran · Jan 30, 2012 at 10:42 PM
Editing: I just noticed that you are using RemoveAt, which means the array is a JS array.
Just use Pop():
LastItem = Array.Pop()
This would remove the last entry from the array and assign it to LastItem.
Shift() would remove from the beginning.
it is a built in array. I'm using the Pop like so:
else if(hit.transform.GetComponent("ObjectSelected").isSelected == true && dragging)
{
var secondLastItem = selected[selected.length-1].gameObject;
if(hit.gameObject == secondLastItem){
selected[selected.length-1].transform.GetComponent("ObjectSelected").Selected(false);
hit.transform.GetComponent("ObjectSelected").isSelected == false;
selected.Pop();
}
But this results in a toggle on the first object. How could access the second last object in the array, i get errors on array[array.length-2]...
i.e. i get " Index is less than 0 or more than or equal to the list count." when using:
else if(hit.transform.GetComponent("ObjectSelected").isSelected == true && dragging)
{
for(var zz : int = selected.length-1; zz >= 0; zz--){
zz -= 1;
var secondLastItem = selected[zz].transform;
if(hit.transform == secondLastItem){
selected[selected.length-1].transform.GetComponent("ObjectSelected").Selected(false);
hit.transform.GetComponent("ObjectSelected").isSelected == false;
selected.Pop();
}
Which works, but i'd like to not have any errors...
Bracket any operations on the array with an
if (Array[x]) { }
In other words, test to make sure there is a value where you are about to manipulate, before you do it.
Or if you are going to manipulate selected[selected.length-2], then test to make sure that selected.length >= 2.
Thanks for the help Tassaran. I ended up testing against >2, which worked.
Your answer
![](https://koobas.hobune.stream/wayback/20220613063550im_/https://answers.unity.com/themes/thub/images/avi.jpg)