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