Instantiate a minimum of gameObject (instantiate un nombre minimum de gameObject)

hi everybody, i’m a begginer and i tried to spawn item at random spots.
but i need to spawn a minimum of gameObject, like 7.
actually, it spawns a random number of gameObject.

here is my code to spawn :

void Start() {

	for (int i = 0; i < spawnPosition.Length; i++){

		int itemToCreate = Random.Range(0, 3);
		if (itemToCreate == 0) {
			itemInScene.Add(Instantiate(diamond, spawnPosition*.position, Quaternion.identity));*
  •   	}*
    
  •   }*
    
  •   scoreCount = 0;*
    
  •   level = 1;*
    
  •   highScoreText.text = PlayerPrefs.GetInt("BEST").ToString();*
    
  • }*
  • public void MoreDiamond (){*
  •   bool checkItemInScene = true;*
    
  •   for (int i = 0; i < spawnPosition.Length; i++){*
    
  •   	int itemToCreate = Random.Range(0, 10);*
    
  •   	if (itemToCreate >= 5) {*
    

_ tempDiamond = (GameObject)Instantiate (diamond, spawnPosition .position, Quaternion.identity);_
* tempDiamond.transform.name = “Diamond_” + Random.Range (0, 100).ToString(“000”);
_
tempDiamond.GetComponent ().DiamondUpgrade (level);_
_
itemInScene.Add(tempDiamond);_
_
diamondScript.Add(tempDiamond.GetComponent());*_

* } else if (itemToCreate == 1 && checkItemInScene) {*
_ itemInScene.Add (Instantiate (itemBall, spawnPosition .position, Quaternion.identity));
checkItemInScene = false;//<- instantiate autre chose

* }
}
}*_

2 Answers

2

You are currently randomly choosing wether you’re spawning an object or not. If I understand correctly, you should instead have an int called minimumNumberOfObjects or something like that, then :

     for (int i = 0; i < minimumNumberOfObjects; i++){
             itemInScene.Add(Instantiate(diamond, spawnPosition*.position, Quaternion.identity));*

}
Using this, your FOR loop will go until it reached your magical minimumNumberOfObjects int.

And if you want them to choose the spawnPosition randomly, then you do this : for (int i = 0; i < minimumNumberOfObjects; i++){ int pickedPosition = Random.Range(0, spawnPosition.Length); itemInScene.Add(Instantiate(diamond, spawnPosition[pickedPosition].position, Quaternion.identity)); }

P.S. Je parle français ;)

// calculate amount of spawns
int minimumSpawns = 7;
int maximumSpawns = 10;
int amountOfSpawns = Random.Range(minimumSpawns, maximumSpawns);

        // instantiate objects at random positions
        for (int i = 0; i < amountOfSpawns; i++) {
            int randomPositionIndex = Random.Range(0, spawnPosition.Length);
            itemInScene.Add(Instantiate(
                    diamond, 
                    spawnPosition[randomPositionIndex].position, 
                    Quaternion.identity));
        }