- Home /
Destroy last object in generic.list
How do I destroy the last gameObject thats been added to a list?
I'm trying to construct a city building game with a road builder tool. For simplicity I wont get into detail, but when the road tool is active and the player is placing road segments, each segment gets added to a generic.list. When the player clicks the right mouse button, they should be able to destroy the road segments one by one. starting from the last segment that was instantiated to the first one.
Heres a small snipit of code from my script.
if(Input.GetMouseButtonDown(1)) {
referenceOn = false; if(roadList !=0){ for ( var roadClone in roadList){ Destroy(roadClone);
}
}
Answer by farooqaaa · Mar 29, 2012 at 09:52 AM
You can use a reverse for-loop. It will start from the last one and iterate towards the first one:
if(Input.GetMouseButtonDown(1))
{
referenceOn = false;
if(roadList)
{
for (var i=roadList.Count; i>0; i--) {
Destroy(roadList[i]);
}
}
}
when I try your script I get a ArgumentOutOfRangeException. There are gameObjects in the list though.
Also it appears that the script would destroy all of the gameObjects in the list. I want to destroy each road one by one when the player clicks the R$$anonymous$$B.
Your answer
Follow this Question
Related Questions
Road Texture Is Stretching 3 Answers
Curved Roads 1 Answer
A node in a childnode? 1 Answer
missingGameObject problem 3 Answers