- Home /
Sorting a list based of a variable
Hi.
I'm trying to sort a list full of gameObjects based on a int from the scripts attached to the gameObjects. As sorting lists is new territory for me, I've looked at various tutorials and forums on how to do this but no matter what I do, I somehow still end up with errors. I was hoping someone could take a look at my code and let me know what I'm doing wrong.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KartPosition : MonoBehaviour
{
public List<GameObject> players = new List<GameObject>();
public GameObject p1;
int i;
// Update is called once per frame
void FixedUpdate()
{
players.Sort((IComparer<GameObject>)new Compare());
//getting player index
foreach (GameObject element in players)
{
i++;
if (element == p1)
{
Debug.Log(i);
i = 0;
}
}
}
}
private class Compare : IComparer<GameObject>
{
int IComparer<GameObject>.Compare(GameObject _objA, GameObject _objB)
{//getting sctrips from gameObjects
if (_objA.name == "Player1")
{
KartControl aScript = _objA.GetComponent<KartControl>();
KartAI bScript = _objb.GetComponent<KartAI>();
}
else if (_objB.name == "Player1")
{
KartAI aScript = _objA.GetComponent<KartAI>();
KartControl bScript = _objb.GetComponent<KartControl>();
}
else
{
KartAI aScript = _objA.GetComponent<KartAI>();
KartAI bScript = _objb.GetComponent<KartAI>();
}
//checking checkpoint variables
if (aScript.cpNumb == bScript.cpNumb)
{
float aDist = Vector3.Distance(aScript.cp[0].transform.position, _objA.transform.position);
float bDist = Vector3.Distance(bScript.cp[0].transform.position, _objB.transform.position);
if (aDist < bDist)
{
t1 = 2;
t2 = 1;
}
else
{
t1 = 1;
t2 = 2;
}
}
else
{
t1 = aScript.cpNumb;
t2 = bScript.cpNumb;
}
return t1.CompareTo(t2);
}
}
Thanks
Answer by Kishotta · Sep 18, 2017 at 05:41 AM
If you import System.Linq
you can do:
MyGameObjectList = MyGameObjectList.OrderBy (e => e.GetComponent<MyComponent> ().MyComponentMember).ToList ();
Your answer
Follow this Question
Related Questions
Find index of item in list 1 Answer
How can i rotate object by pressing on key R and keep object facing to me my self ? 0 Answers
How can i spawn new gameobjects to be inside the terrain area ? 2 Answers
How can i change vertex posiiton to push it back -1 on z ? 1 Answer
How can i use a bool to decide when to move the character or not ? 2 Answers