Hi, I make a turn-based game, and in the start of game all of characters sending from their scripts a message to Fight-Manager Script, and Figth-Manager Script has sort the speedList and next it sending an message to the fastest character. But, I dont know what do this… I know that the standart list have a void Sort() but later i must send back to the fastest character a permission to move.
This is my test sort script:
it have two lists, and it have to sort both, so that the “first” of theList2 was on the same index as the biggest int from theList. This is only example and it not work because some values may be the same and i dont know what to do. Please help.
it would probably be better to store the “scripts” in the list rather than just the speed numbers, if you include “System.Linq” namespace you can then sort the list by their member attributes using the syntax demonstrated below:
using UnityEngine;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class FightManager : MonoBehaviour
{
public List<Fighter> fighters;
void Start ()
{
fighters = GameObject.FindObjectsOfType<Fighter>().ToList(); // grab all the fighter scripts in the scene
StartCoroutine(TakeTurn());
}
IEnumerator TakeTurn()
{
fighters = fighters.OrderBy(f => f.speed).ToList(); // sort the list by their "speed" attribute
Debug.Log("Turn start");
for (int i=0;i<fighters.Count;i++)
{
StartCoroutine(fighters[i].Attack());
yield return new WaitForSeconds(1f);
}
Debug.Log("Turn over");
}
}
using UnityEngine;
using System.Collections;
public class Fighter : MonoBehaviour
{
public FightManager fightManager;
public float speed;
void Awake ()
{
speed = Random.Range(0f, 10f);
fightManager = FindObjectOfType<FightManager>();
}
public IEnumerator Attack()
{
Debug.Log(gameObject.name + " attacked");
yield return new WaitForSeconds(1f);
}
}
LINQ comes at a huge performance cost for some platforms. Why don’t you just use a SortedList? Add objects based on their speed and get the last object (because its key which is its speed would be greatest). This completely eliminates the need for lookups or LINQ.