CodexBloom - Programming Q&A Platform

Sorting a Custom Game Object Array by Multiple Properties in Unity - Issues with Performance

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-09-07
unity performance sorting C#

I've spent hours debugging this and After trying multiple solutions online, I still can't figure this out... Currently developing a 2D platformer in Unity, and I need to sort an array of custom game objects based on multiple properties: their position and speed. The goal is to order them primarily by their Y position (to handle layering) and secondarily by speed, since the faster objects should appear top in the same Y layer. I've tried using LINQ for this, but I'm worried about performance as my object count grows. Here's the approach I started with: ```csharp using System.Linq; public class GameObjectProperties { public float YPosition; public float Speed; } public void SortGameObjects(GameObjectProperties[] objects) { var sortedObjects = objects.OrderBy(o => o.YPosition) .ThenByDescending(o => o.Speed) .ToArray(); } ``` This works fine for smaller arrays, but I notice frame drops when the number of objects exceeds 200. To mitigate this, I've thought about implementing a custom sorting method to control the sort's complexity. I've also considered using a more manual approach with a quicksort or mergesort implementation. Would a custom sort method enhance performance significantly? Below is my attempt at a quicksort implementation: ```csharp public void QuickSort(GameObjectProperties[] array, int low, int high) { if (low < high) { int pi = Partition(array, low, high); QuickSort(array, low, pi - 1); QuickSort(array, pi + 1, high); } } private int Partition(GameObjectProperties[] array, int low, int high) { GameObjectProperties pivot = array[high]; int i = low - 1; for (int j = low; j < high; j++) { if (array[j].YPosition < pivot.YPosition || (array[j].YPosition == pivot.YPosition && array[j].Speed > pivot.Speed)) { i++; Swap(array, i, j); } } Swap(array, i + 1, high); return i + 1; } private void Swap(GameObjectProperties[] array, int i, int j) { var temp = array[i]; array[i] = array[j]; array[j] = temp; } ``` The sorting seems to work, but I haven't benchmarked it yet. I'm just concerned that the way I've set up the partitioning is not optimal. Would love to hear suggestions on how to improve the sorting logic or if there are better practices for sorting in Unity that ensure smooth gameplay performance. My development environment is Ubuntu. Any help would be greatly appreciated! This is happening in both development and production on Windows 11. Thanks for any help you can provide!