This is a C# method I found in a Unity3D tutorial:
Public List<Piece> pieces = new List<piece>(); // list of pieces in the pool
public Piece GetPiece(PieceType pt, int visualIndex) {
Piece p = pieces.Find(x => x.type == pt && x.visualIndex == visualIndex);
}
What I don't understand is in this line : x => x.type == pt...
Where does the "x" come from and why x.type?
This is List<T>.Find
and has nothing to do with GameObject.Find
!
Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire
List<T>
.The
Predicate<T>
is a delegate [(or in your case lambda expression)] to a method that returnstrue
if the object passed to it matches the conditions defined in the delegate. The elements of the currentList<T>
are individually passed to thePredicate<T>
delegate, moving forward in theList<T>
, starting with the first element and ending with the last element. Processing is stopped when a match is found.
Then what you have there is a Lambda Expression where x
is the iterator variable like in
foreach(var x in pieces)
that is where the x
comes from. It can basically called whatever you like. And its type is Piece
so it depends on your Piece
implementation what x.type
is .. looking on your parameters I'ld say it is an enum
called PieceType
.
So it does basically the same as and is just a shorthand for
public Piece GetPiece(PieceType pt, int visualIndex)
{
foreach(var x in pieces)
{
if(x.type == pt && x.visualIndex == visualIndex) return x;
}
return default;
}