remove empty array element unity code example
Example 1: unity clear array
for (int i = 0; childs.Length; i++) { childs[i] = null // or childs[i] = 0; }
Example 2: remove empty values from array unity
int LevelSelection; [HideInInspector] public GameObject[] disabledMap; void LoadLevel() { //sets the disabled array to the amount of map sections disabledMap = new GameObject[LevelObjects.Length]; int dissabledArrayCount = 0; //iterates through all map sections for (int i = 0; i < LevelObjects.Length; i++){ //checks if current iteration is enabled if (LevelObjects[i].activeSelf == false) { //if the map section is enabled it adds it to a separate array. disabledMap[dissabledArrayCount] = LevelObjects[i]; dissabledArrayCount++; print("added to array."); } } //debug print("Length :" + disabledMap.Length); //Clears empty indexes here. //chooses a random map section from the array of disabled map sections. int levelChoice = Random.Range(0, disabledMap.Length); print("Level choice :" + levelChoice); disabledMap[levelChoice].SetActive(true); disabledMap[levelChoice].transform.position = new Vector3(0, 0, LastLoad + 30); }
Example 3: remove empty values from array unity
GameObject[] gameObjectArray = new GameObject[] { new GameObject(), new GameObject(), new GameObject() }; // example GameObject Array List<GameObject> gameObjectList = new List<GameObject>(gameObjectArray); gameObjectList .RemoveAll(x => x == null); gameObjectArray = gameObjectList .ToArray();