I have an array of Transforms in 2d that I want to sort by their positions in this way:
if you pressed right:
Create a sorted list of the objects from Right to Left.
if you pressed left:
Create a sorted list of the objects from Left to Right.
if you pressed Up:
Create a sorted list of the objects from Up to Down.
if you pressed Down:
Create a sorted list of the objects from Down to Up.
This is the code I worte:
void UpdateRobotsOrder(Vector2 movement)
{
robotsOrder = new List<iRobotScript>();
int h = 0;
float minimax = 0;
List<Transform> temps = new List<Transform>();
foreach (Transform rob in allRobots)
{
temps.Add(rob);
}
//Transform[] news = new Transform[temps.Count];
if (movement.x > 0)
{
minimax = -100;
for (int u = 0; u < allRobots.Length; u++)
{
for (int i = 0; i < temps.Count; i++)
{
if (temps[i].position.x > minimax)
{
//news[i] = temps[i];
minimax = temps[i].position.x;
h = i;
}
}
robotsOrder.Add(temps[h].GetComponent<iRobotScript>());
temps.Remove(temps[h]);
}
}
if (movement.x < 0)
{
minimax = 100;
for (int u = 0; u < allRobots.Length; u++)
{
for (int i = 0; i < temps.Count; i++)
{
if (temps[i].position.x < minimax)
{
//news[i] = temps[i];
minimax = temps[i].position.x;
h = i;
}
}
robotsOrder.Add(temps[h].GetComponent<iRobotScript>());
temps.Remove(temps[h]);
}
}
if (movement.y > 0)
{
minimax = -100;
for (int u = 0; u < allRobots.Length; u++)
{
for (int i = 0; i < temps.Count; i++)
{
if (temps[i].position.y > minimax)
{
//news[i] = temps[i];
minimax = temps[i].position.y;
h = i;
}
}
robotsOrder.Add(temps[h].GetComponent<iRobotScript>());
temps.Remove(temps[h]);
}
}
if (movement.y < 0)
{
minimax = 100;
for (int u = 0; u < allRobots.Length; u++)
{
for (int i = 0; i < temps.Count; i++)
{
if (temps[i].position.y < minimax)
{
//news[i] = temps[i];
minimax = temps[i].position.y;
h = i;
}
}
robotsOrder.Add(temps[h].GetComponent<iRobotScript>());
temps.Remove(temps[h]);
}
}
}
This dosen’t seems to work for me… it works only if the first transform in the allRobots array is also the first in the robotsOrder list, otherways it debugs an error - Argument is out of range :\
I actually managed to make it work but not in the best way (I checked all the positions in the grid by specific order instead of just check the objects positions)…
Also i tried to use Array.OrderBy and list.Sort with no success. please help!