- Home /
spawning game objects
I have this script that spawns objects from the center of the game object, I want the script to spawn the objects randomly from the object, rather than only from the center how can i do this?
[SerializeField] float secondsBetweenSpawns = 2f;
[SerializeField] GameObject enemyPrefab;
void Start()
{
StartCoroutine(SpawnBlocks());
}
IEnumerator SpawnBlocks()
{
while (true)
{
Instantiate(enemyPrefab, transform.position, Quaternion.identity);
yield return new WaitForSeconds(secondsBetweenSpawns);
}
}
}
Answer by PanzerPotato · Jun 03, 2018 at 12:10 AM
Try this position: transform.position + (new Vector3 (Random.insideUnitCircle.x, 0f, Random.insideUnitCircle.z) * radius)
. This will spawn objects on a flat (face-up) circle around the object. If you want it in a sphere, change 0f to Random.insideUnitCircle.y. If you want it on the edge of the circle, use Random.onUnitCircle instead of Random.insideUnitCircle.
where do i need to place that pice of code? I got an error where i placed it so i think i put it in the wrong spot
Put it in your Instantiate () part, replacing transform.position
.