Generating and Sorting Number with C# Unity IN wEBgl

A simple sorting application using Unity C# Array. How to use an array for sorting was one of the technical question that came up during a course interview recently. I have a personal preference for Lists, which I used mostly for ‘Splotches‘ coding. Lists are slower than arrays but provide easier access point to data. It would probably make more sense to use array when there is a large amount of data to work on.¬†This article covers a bit more than the original question on how to sort numbers with array. It includes how to generate random number with array, sort them and reproduces the list in a single string, result in OOP.¬† Included at the end of this article is a simple WebGL application to demonstrate the sorting of array elements.

The elements are randomly generated, added to the Array during the run in the FOR loop. The class items and methods include:

  • Create and Sorting: ShowResult (public method so it can be accessed by the Button class)
  • Array Name: generatedList
  • No. of Elements in Array: numberInSet (Class public integer, set at 5)
  • Sort in Ascending Order: Array.Sort(generatedList)
  • Sort in Descending Order: Array.Reverse(generatedList)
  • Convert and Combine Array Elements into a Single String: ConvertIntegerArrayToSingleString Method (Take in an array, return a single string)
  • Namespace: using System
public void ShowResult()
{
int count = numberInSet;//No. of elements in the Array, default 5.
int[] generatedList = new int[count];

for (int i = 0; i < count; i++)
{
int j = UnityEngine.Random.Range(1,10); //Randomly generated number
generatedList[i] = j;
}

// Unsorted, converted to string.
generatedText.text = "Generated: " 
+ ConvertIntegerArrayToSingleString(generatedList);

//Sorted in default ascending order, converted to string.
Array.Sort(generatedList);
sortedText.text = "Sorted: " 
+ ConvertIntegerArrayToSingleString(generatedList); 

//Sorted in reverse descending order, converted to string.
Array.Reverse(generatedList);
sortedReverseText.text = "Sorted Reverse: " 
+ ConvertIntegerArrayToSingleString(generatedList); 
}

string ConvertIntegerArrayToSingleString(int[] arrayList)
    {
        string arrayString = "";

        for (int i = 0; i < numberInSet; i++)
        {
            if(i!= (numberInSet - 1))
            {
                arrayString += arrayList[i].ToString() + ", ";
            }
            else
            {
                arrayString += arrayList[i].ToString();
            }

        }
        
        return arrayString;
    }

C# Array Sort with Unity – WebGL Application
Generating randomness and probability in game object programming are basic skills. The coding for generating no repeat random numbers with Unity and C# is the topic covered here.

Published by Trine Epiphany

Leave a Reply

Your email address will not be published. Required fields are marked *