- Home /
How to rearange the order of a list after an item was removed?
so, I have an endless runner and I create a new prefab when the player is a certain distance fromte last part. I have a list of these prefabs and the code chooses a random part every time it needs to spawn a new platform. I then add these spawned parts to a second list. In order to not run out of memory, I want to remove the first element in this second list when the list has 10 elements in it. Is there a way to reorder the list so that all elements move down one place ? I will post my code under here, sorry if my explenation is not the best, ask my about it in the comments if you don't get something. Thanks in advance.
using System.Collections.Generic; using Unity.Mathematics; using UnityEngine; using Random = UnityEngine.Random;
public class SpawnManager : MonoBehaviour { private const float PlayerDistanceSpawnLevelPart = 150f; private Vector3 lastEndPosition;
[SerializeField] private Transform _levelPartStart;
[SerializeField] private List<Transform> _partsList;
[SerializeField] private Player player;
[SerializeField] private List<Transform> _spawnedParts;
void Awake()
{
lastEndPosition = _levelPartStart.Find("EndPosition").position;
}
void Update()
{
Vector3 playerPosition = player.transform.position;
if (Vector3.Distance(playerPosition, lastEndPosition) < PlayerDistanceSpawnLevelPart)
{
SpawnLevelPart();
}
if (_spawnedParts.Count > 10)
{
_spawnedParts.Remove(_spawnedParts[0]);
foreach (var part in _spawnedParts)
{
//here I would like to reorder the list so that the next time this is called, I don't get a null
//reference exception
}
}
}
private void SpawnLevelPart()
{
Transform chosenLevelPart = _partsList[Random.Range(0, _partsList.Count)];
Transform lastLevelPartTransform = SpawnLevelPart(chosenLevelPart,lastEndPosition);
_spawnedParts.Add(chosenLevelPart);
lastEndPosition = lastLevelPartTransform.Find("EndPosition").position;
}
private Transform SpawnLevelPart(Transform levelPart, Vector3 spawnPosition)
{
Transform levelPartTransform = Instantiate(levelPart, spawnPosition, quaternion.identity);
return levelPartTransform;
}
}
I was thinking using a foreach loop but I don't know if that will work?
Your answer
![](https://koobas.hobune.stream/wayback/20220613032703im_/https://answers.unity.com/themes/thub/images/avi.jpg)