- Home /
На вопрос ответили. Правильный ответ был принят
How to remove an item from a list of custom variables
I have an intVector2 class
public class intVector2
{
public int x;
public int y;
public intVector2(int _x, int _y)
{
x = _x;
y = _y;
}
}
In other script, I have created a list of them
List<intVector2> allowedPoss = new List<intVector2>();
How do I remove some items from it?
allowedPoss.Remove(new intVector2(1, 1)); //Doesn't works
P.S. sorry for my English.
Answer by NoseKills · Aug 15, 2016 at 07:16 PM
allowedPoss.Remove(new intVector2(1, 1));
doesn't work because on this line you create a new intVector2() using its constructor. The vector you create on this line is not in the list so it can't be removed either. Perhaps you have added another vector that has the same x and y values to the list but it is not the same vector.
As the C# documentation explains the object you pass in as the parameter to Remove is compared to the items on the list using IEquatable.Equals() if your class implements that interface. That's the key. Implement that interface to your intVector class and the Remove method will know which vectors should be considered "the same"
public class intVector2 : IEquatable<intVector>
{
public int x;
public int y;
public intVector2(int _x, int _y)
{
x = _x;
y = _y;
}
public bool Equals(intVector2 other)
{
if (other == null)
return false;
return other.x == x && other.y == y;
}
}
Your other options are to use RemoveAt() to remove from a specific index or to hold a refere nice to the vector you need to remove and use when you call Remove.
Hope I didn't make too many typos. I'm on mobile.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How to Find all objects with Tag and List their Transforms? 4 Answers
Update list on mouse click 1 Answer
List.Add (new CustomClass()) results in empty entry 1 Answer