My code freezes Unity...

Hello.

I have some code used to pick some random objects from an array and makes sure the same objects isn’t picked twice.

Here’s my function that get’s called to make the array.

//Used to update the shapes.
	void UpdateShapes ()
	{        
		int count = 3 + (2*currentLevel);
		usedObjects.Clear();

		List<GameObject> tempGameObjectsToSpawn = new List<GameObject>();

		
		//For each int in Count
		for(int i = 0; i < count; i++)
		{
			//Make a bool called ItemFound and set it to false.
			bool itemFound = false;

			//While ItemFound is false(No item has been found)
			while(itemFound == false)
			{
				//Make a new int.
				int r = Random.Range(0, shapeObjects.Length);

				//If the list "UsedObjects" contains "r"
				while(usedObjects.Contains(r))
				{
					//Set "r" to something new.
					r = Random.Range(0, shapeObjects.Length);
				}
				//After this. add "r" to the usedObjects list.
				usedObjects.Add(r);

				//If the list "UsedObjects" doesn't contain the "r" int.
				if(!usedObjects.Contains(r))
				{
					//Then set the itemFound bool to true which stops the code for this object.
					itemFound = true;
				}
			}
		}


		//For each int in usedObjects list
		for(int ii = 0; ii < usedObjects.Count; ii++)
		{
			int index = usedObjects[ii];
			tempGameObjectsToSpawn.Add(shapeObjects[index]);
		}


		// Fill 2 temp arrays in the end.
		TempClonedObjects = GameObject.FindGameObjectsWithTag("Clone");
		TempSameObjects = GameObject.FindGameObjectsWithTag("Same");
	}

Here’s my code used to instantiate all the GameObjects.

void InstantiateObjects(List<GameObject> objectsToSpawn)
	{
		for (int i = 0; i < objectsToSpawn.Count; i++)
		{
			//Spawn the object(position 0, 0, 0)
			GameObject obj = (GameObject)GameObject.Instantiate(shapeObjects*);*
  •  	// Calculate random values for X,Y,Z and set location of new object*
    
  •  	float x = Random.Range(minX, maxX);*
    
  •  	float y = Random.Range(minY, maxY);*
    
  •  	float z = 0;*
    
  •  	obj.transform.position = new Vector3(x, y, z);*
    
  •  	//If it's the last or next last object to spawn, the tag will be set to "Same"*
    
  •  	if(i == objectsToSpawn.Count || i + 1 == objectsToSpawn.Count)*
    
  •  	{*
    
  •  		obj.tag = "Same";*
    
  •  	}*
    
  •  	// Else set it to "Clone"*
    
  •  	else{*
    
  •  		obj.tag = "Clone";*
    
  •  	}*
    
  •  }*
    
  • }*
    I’m not getting any errors in the console so it’s weird that it won’t work.
    The program just freezes and won’t respond.

What exactly are you trying to do with these lines?

usedObjects.Add(r);
 
if(!usedObjects.Contains(r))
{
    itemFound = true;
}

You’re adding r to that list and then only ending the loop if it doesn’t exist, AFAIK it will always exist and if a loop never ends Unity will freeze. I think just removing ! will make it behave how you want.