C# List index confusion using Mathf.Clamp

I have an object that is made up of say around 24 separate platforms that are connected in a 4X6 rectangle. I am attempting to make these platforms fall from the back to the front by setting isKinematic on their rigidbody from true to false. Before I continue explaining here is the part of the code that makes the platforms fall.

IEnumerator FallPlatforms (){
		
	

		while (Platforms.Count > 0){
			int x = Random.Range (0, 5);
			Mathf.Clamp (x, 0, Platforms.Count-1);
			print ("X:" + x + " Platform Count:" + Platforms.Count);
			if (Platforms [x] == null) {
				break;
			}
			Rigidbody rigi = Platforms [x].gameObject.GetComponent<Rigidbody> ();
			if (rigi != null) {
				rigi.isKinematic = false;
			}
			Platforms.Remove (Platforms[x]);

			yield return new WaitForSeconds ((0.02f)*difficulty);
		}
	}

The falling is supposed to be somewhat random, but still from the back to the front. Therefore I choose a random index between 0 and 5, I use Mathf.Clamp to make sure the random index is within the range of the list Platforms, then I cause that platform to fall, then I remove it form the list. It works perfectly until there gets to be 2 platforms left. Unity returns a “ArgumentOutOfRangeException: Argument is out of range.” in the Debug Log.

Mathf.Clamp and Random.Range are both inclusive according to Unity’s documentation.

As you can see I placed print (“X:” + x + " Platform Count:" + Platforms.Count); to help try and figure out this problem. Right before Unity gives me the error, the print statement reads: “X:2 Platform Count:2”. Yet, this should be impossible, because if Platforms.Count = 2, then my mathf.Clamp call should clamp x between 0 and 1 (effectively making x = 1). I am completely lost on how and why this is happening and any help would be greatly appreciated. Thanks!

You’re not assining the return value of Mathf.Clamp to anything. So basically this line does nothing.

BTW: If you’re passing integers, Random.Range is not inclusive. Passing 0 and 5 will return 4 at max. I’m not sure why you need the clamp anyway. Why don’t you just pass 0 and Platforms.Count to Random.Range?