- Home /
does not implement right interface
I don't know how to solve this kind of issue. I have 5 gameobjects that listed in my List(). the issue was when i tried to sort the list there's an error "ArgumentException: does not implement right interface". The listOfGameobject already contains 5 slots for 5 gameobject in editor and already filled.
I'll show my codes:
public List<Transform> listOfGameobject;
private bool toggleMenu = false;
void Update()
{
if (Input.GetKeyUp(KeyCode.M))
{
toggleMenu = !toggleMenu;
}
}
void OnGUI()
{
if (toggleMenu)
{
for (int i = 0; i < listOfGameobject.Count; i++)
{
if (GUI.Button(new Rect(Screen.width - 300, (xLocation + 25) * i, 300, 25), listOfGameobject[i].name))
{
Debug.Log(listOfGameobject[i].name);
}
}
}
if (GUILayout.Button("Sort"))
{
listOfGameobject.Sort();
}
}
Answer by whydoidoit · Sep 09, 2012 at 09:25 AM
Things that are sorted need to implement the IComparable interface or you need to create an class that implements IComparer on a class and pass an instance of that to sort.
The problem is - what are you sorting these things on? Transform doesn't implement IComparable because there is no obvious order for transforms. Your easiest way might be to use Linq:
using Linq;
...
listOfGameObject = listOfGameObject.OrderBy(t=>t.position.z /* Or whatever */).ToList();
@whydoidoit loves Linq ;)
In this case, I'm guessing that the sort criterion could be the distance from origin. Since calculating the magnitude is a bit expensive, I would rather use the squared magnitude:
listOfGameObject = listOfGameObject.OrderBy(t=>t.position.sqr$$anonymous$$agnitude).ToList();
Old thread, but still useful! Thanks to @whydoidoit, I was able to sort a List of GameObjects by name, so that I could then create a dynamic UI scrollable selection list. $$anonymous$$y code is:
AllThirdPersonObjects = AllThirdPersonObjects.OrderBy(g => g.name).ToList();
(AllThirdPersonObjects is, obviously, a List.) For anyone unfamiliar with the lambda expression (=>), the "g" variable is essentially arbitrary, just like the "t" in the above example. Just pick a letter (or something longer), put one in front of the => and then put another one after it, along with the property you want to sort by.
Your answer
![](https://koobas.hobune.stream/wayback/20220613080817im_/https://answers.unity.com/themes/thub/images/avi.jpg)