Spawning enemies using insideUnitCircle :
I'm trying to create a prefab, that I can place anywhere on a map (2D top down shooter) using insideUnitCircle to randomise the spawns somewhat but keeping them inside a general area and not outside of map boundaries. Here is my script so far:
public class SpawnCircle : MonoBehaviour {
public GameObject enemyType;
public int enemyCount;
public float spawnDelay;
public float spawnRate;
public float spawnRadius;
private int counter;
// Use this for initialization
void Start (){
counter = 0;
}
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Player") {
Destroy (GetComponent<Collider2D> ());
InvokeRepeating ("Spawn", spawnDelay, spawnRate);
}
}
void Spawn() {
Instantiate(enemyType, transform.position = Random.insideUnitCircle * spawnRadius, transform.rotation);
counter = counter + 1;
if (counter == enemyCount)
Destroy (this.gameObject);
}
} Unfortunately this will place the centre of the spawn area at map co-ordinates 0,0.
How can i move the centre of the circle to where i have placed my prefab? Any help would be much appreciated.
Answer by bhuddaboom · May 12, 2016 at 10:02 AM
Ok, after a little research i found this: http://answers.unity3d.com/questions/500369/teleport-using-randominsideunitcircle-relative-to.html and changed my code to:
newPosition = Random.insideUnitCircle * spawnRadius;
newPosition.x += transform.position.x;
newPosition.y += transform.position.y;
Instantiate (enemyType, transform.position = newPosition, transform.rotation);
newPosition.x = 0;
newPosition.y = 0;
(I needed to reset newPosition each time so the spawnpoint won't wander all over the map)
Answer by NoseKills · May 10, 2016 at 10:29 PM
Add the random position to the SpawnCircle's current position
Instantiate(enemyType, transform.position + (Random.insideUnitCircle * spawnRadius), transform.rotation);
What you previously had inside the Instantiate() call
transform.position = Random.insideUnitCircle * spawnRadius
was setting the SpawnCircle's position to a random spot around 0,0 and spawning the item in that same place.
Hmm, this gives me this error: Assets/SpawnCircle.cs(30,51): error CS0121: The call is ambiguous between the following methods or properties: UnityEngine.Vector2.operator +(UnityEngine.Vector2, UnityEngine.Vector2)' and
UnityEngine.Vector3.operator +(UnityEngine.Vector3, UnityEngine.Vector3)'
Your answer
![](https://koobas.hobune.stream/wayback/20220612080505im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to spawn a prefab every 5 second randomly between a set range? 0 Answers
How to make multiple objects spawn at random order and move ? 1 Answer
I need help making my objects spawn correctly. 0 Answers
Random.Onunitsphere confusing different spheres 1 Answer
Making an object spawned from a list became a child of the player? 0 Answers