Sorting GameObjects By Values

Hello to everyone,
I have a float array (public float[ ] CompanyMarketShares) ;
And in the same script, I have a GameObject array ( public GameObject[ ] Companies) ;
Both of the arrays have 4 elements. CompanyMarketShare[0] is Company[0]'s marketshare. And I want sort this Companies by the values of MarketShares. How can I do that?

My recommendation would be to create a MonoBehavior class (for example, CompanyController) that has a float MarketShare property, and put the CompanyController on your Company game objects. Then, in your script, you find all the CompanyController instances in your scene, and keep them in a list/array, and sort it however you like as the need arises. The CompanyController instance will have a property for the MarketShare value, and a handle back to the gameObject itself.

A similar answer from me. You can create a class to contain both values. You can put them in a list or array and then sort by the market share. When you want to display them, they will be in the right order. The class needn’t be a monobehaviour, though.

I would ditch the two arrays and create a dictionary instead, since you’re associating a value (market share) with an object (company), which is exactly what dictionaries are for.

Dictionary<Company, float> marketShare = new Dictionary<Company, float>();

// add your companies to the dictionary

Then when you need a list of companies sorted by their market share, you can create a list and use the dictionary as your sort lookup.

private List<Company> GetCompaniesSortedByMarketShare()
{
  List<Company> results = new List<Company>(); // you can reuse this list instead of creating it every time depending on how often you call this

   // add all the companies you're interested in getting data for

  results.Sort(CompareByMarketShare);

  return results;
}

private int CompareByMarketShare(Company a, Company b)
{
  return marketShare[a].CompareTo(marketShare[b]);
}
Array.Sort(CompanyMarketShares, Companies);

will sort both arrays

Array.Sort(CompanyMarketShares.ToArray(), Companies);

will sort only Companies

That’s cool. I actually read about this a couple of weeks ago, but had forgotten. :slight_smile:

Though, I am unfamiliar with the second part, and how that only sorts one. Nevertheless, that’s a good approach.

Well the second one should copy items to a new array, so the new (fake) one is sorted and the original remains untouched. I am 85 % sure about it :slight_smile:

Right, that makes sense. :slight_smile: