Home > OS >  how do I access the bottom of the List?
how do I access the bottom of the List?

Time:05-09

Im trying to figure out how to remove the last GameObject that entered the List. Currently this code has allowed me to "Remove" GameObjects in the order that they were "Add" to the list but id like to instead remove the last one added.

public class GameManager : MonoBehaviour

List<GameObject> stock = new List<GameObject>();
List<GameObject> waitingRoom = new List<GameObject>();


public void PayStock()
{
 GameObject topCard = stock[0];
    
    stock.Remove(topCard);
    waitingRoom.Add(topCard);
}

CodePudding user response:

I guess Stack collection fits your needs, you described typical LIFO

Use Push to add item and Pop to remove last item from collection (you will also get that item as returned value). So your code will look like:

public class GameManager : MonoBehaviour

Stack<GameObject> stock = new Stack<GameObject>();
List<GameObject> waitingRoom = new List<GameObject>();


public void PayStock()
{
   GameObject topCard = stock.Pop();
   waitingRoom.Add(topCard);
}

If you want to use List you can get last element like:

GameObject topCard = stock[stock.Length-1];
// Or in C# 8.0 
// GameObject topCard = stock[^1];
// Or using System.Linq
// GameObject topCard = stock.Last();

CodePudding user response:

The System.Linq library provides useful extensions to control lists. For example, simply use Last() in your question.

using System.Linq;

public class GameManager : MonoBehaviour
{
    List<GameObject> stock = new List<GameObject>();
    List<GameObject> waitingRoom = new List<GameObject>();
    
    public void PayStock()
    {
        var topCard = stock.Last();
    
        stock.Remove(topCard);
        
        waitingRoom.Add(topCard);
    }
}
  • Related