Skip to content

Instantly share code, notes, and snippets.

@jeniferirwin
Created July 31, 2020 11:28
Show Gist options
  • Save jeniferirwin/4a0ae4c6354232d085264f2992c88725 to your computer and use it in GitHub Desktop.
Save jeniferirwin/4a0ae4c6354232d085264f2992c88725 to your computer and use it in GitHub Desktop.
Shuffle function for Unity, primarily intended for object pools.
/// <summary>
/// This is used for when we're working with an object pool that has
/// a variety of randomized objects and is not seeing frequent heavy use.
///
/// For cases where the object pool has randomized elements (such as
/// enemies with different stats), working with that pool has the
/// possibility of just returning the same exact object every time we
/// request an object from it. For random spawns, we don't want this.
///
/// Shuffle is used to randomly reorder an object pool so that this doesn't
/// happen.
///
/// </summary>
/// <param name="list">The object pool to reorder.</param>
/// <returns>Reordered object pool.</returns>
private List<GameObject> Shuffle(List<GameObject> list)
{
List<GameObject> _newList = new List<GameObject>();
while (list.Count > 0)
{
var _newRandom = Random.Range(0, list.Count);
_newList.Add(list[_newRandom]);
list.RemoveAt(_newRandom);
}
return _newList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment