- Home /
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[i].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 [i].position, Quaternion.identity);
tempDiamond.transform.name = "Diamond_" + Random.Range (0, 100).ToString("000");
tempDiamond.GetComponent<Diamond> ().DiamondUpgrade (level);
itemInScene.Add(tempDiamond);
diamondScript.Add(tempDiamond.GetComponent<Diamond>());
} else if (itemToCreate == 1 && checkItemInScene) {
itemInScene.Add (Instantiate (itemBall, spawnPosition [i].position, Quaternion.identity));
checkItemInScene = false;//<- instantiate autre chose
}
}
}
Answer by marcrem · Oct 18, 2017 at 05:42 PM
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[i].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 < $$anonymous$$imumNumberOfObjects; i++){
int pickedPosition = Random.Range(0, spawnPosition.Length);
itemInScene.Add(Instantiate(diamond, spawnPosition[pickedPosition].position, Quaternion.identity));
}
salut et merci de ton aide en faite, ce que je veux c'est controler le nombre exact de "diamond" qui vont spawn.
je comprend ce que tu as ecrit mais je vois absolument pas ou l'ecrire dans ma methode "more diamond"...
Answer by nenok1 · Oct 18, 2017 at 06:47 PM
// 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));
}
Your answer
