- Home /
How to instantiate prefabs at random postions in 2d
I need to instantiate 20 carrots in a 10x8 grid, i attached the script to the prefab called Carrot with the tag Pickup,.
using System.Collections; using System.Collections.Generic; using UnityEngine; using System;
public class RandomGenerating : MonoBehaviour {
int carrots = 20;
int[] vectorX={0};
int[] vectorY={0};
float randomNumberX=0;
float randomNumberY=0;
public GameObject Carrot;
void Start () {
int ok = 0;
int counter = 0;
int curentNR = 0;
while (counter < carrots) {
randomNumberX = UnityEngine.Random.Range (0, 9);
randomNumberY = UnityEngine.Random.Range (0, 7);
ok = 0;
for (int counter2 = 0; counter2 < curentNR; counter2++) {
if (randomNumberX == vectorX [counter] && randomNumberY == vectorY [counter]) {
ok = 1;
break;
}
}
if (ok == 0) {
Console.WriteLine ("X: " + randomNumberX + ", Y: " + randomNumberY);
vectorX [counter] = (int)randomNumberX;
vectorY [counter] = (int)randomNumberY;
counter++;
curentNR++;
Instantiate(Carrot, new Vector3(randomNumberX, randomNumberY, 0), Quaternion.identity);
}
}
}
}
Answer by Harinezumi · Feb 27, 2018 at 11:05 AM
Your solution is almost correct, but you should have checked all the elements of vectorX
and vectorY
if the space is already occupied, and correctly initialize them to the number of carrots to be generated.
This is a cleaner way:
[SerializeField] int requiredCarrots = 20;
[SerializeField] GameObject carrotPrefab = null;
private void Start () {
if (carrotPrefab == null || requiredCarrots > 10 * 8) { return; } // protect against some errors
bool[,] occupiedPositions = new bool[10, 8]; // you can use a 2D array of bools to store if a position is occupied
for (int i = 0; i < requiredCarrots; ++i) {
int x, y; // need to declare variables used in while condition before the do-while
do {
// Random.Range(int, int) is inclusive-exclusive
x = Random.Range(0, 10);
y = Random.Range(0, 8);
} while (occupiedPositions[x, y]);
occupiedPositions[x, y] = true;
Instantaite(carrotPrefab, new Vector3(x, y, 0), Quaternion.identity);
}
}
Thank you for you answer. I still have a problem: UnityEngine.Quaternion does not contain a definition for 'Identity'
Sorry, it's Quaternion.identity
with lower-case i. I updated the answer.
The program is running, but on my scene the carrots still don't appear. What could be the problem?
You need a game object in the scene that has this script on it, and assign to the carrotPrefab
field the game object that represents your carrots. Important, the carrot game object must NOT have this script on it, or you start to spawn infinite carrots!