- Home /
Array Reordering?
I cannot use a List. I have a set amount of Elements in an array, don't need to add or remove any- just need to be able to switch the Elements to different positions in the Array.
For example, I have a check that looks for an empty array. If the array behind it (index i + 1 ) DOES have a value, then the array that has something in it will replace the one that has nothing.
I also would like to be able to reorder based on an Element's variable (int) and this needs to be done in an Update() function of some kind.
Here is an example of my code I'm working on.
friendsList is a custom class Array. friendLabel is a GameObject[] with UI elements in the children.
for(int i = 0; i < friendsList.Length; i++)
if (friendsList.ElementAt (i).frienduser != null)
{
friendLabel[i].SetActive(true);
friendLabel[i].GetComponentInChildren<Text>().text = friendsList.ElementAt (i).frienduser + " \n *"
+ friendsList.ElementAt(i).friendStatusMessage;
// turn their state into the corresponding sprite imge!
friendLabel[i].GetComponentInChildren<Image>().sprite = statuses[friendsList.ElementAt (i).state];
}
else //frienduser is null
{
friendLabel[i].SetActive(false);
if (friendsList.ElementAt (i + 1).frienduser != null)
{
//if we have something behind this slot that is not empty, replace this empty one with the full one!
//friendsList.Equals(friendsList.ElementAt (i + 1); // = friendsList.ElementAt (i + 1); Doesn't work. : ^ (
}
}
There is a library that helps reordering arrays/lists.
Its called System.Linq
If you don't want to use any managed or utilized arrays / lists / etc (incl Generics 'n Linq) then you need to implement all by your own.
The last line does not work because at the end of the array i + 1 exceeds the array's length and thus is out of scope. You should add a check
if (i + 1 < friendsList.Length)
Your answer
![](https://koobas.hobune.stream/wayback/20220612000313im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Instantiating gameobjects in an array / class problem | NullReferenceException: 0 Answers
JSON missing arrays 1 Answer
How to access a variable within a multidimensional array of class 2 Answers
Problem with Singleton and NullReferenceException? 0 Answers
Need my function to work with different lists of different values (classes) 1 Answer