- Home /
making a no-spawn-zone with triggers
making a game that after every round, asteroids will spawn randomly on the screen instead of inside a 2d circle collider that I set up in the middle of the screen. But my code doesn't seem to be working. Here's the code...
void Start () {
safeZone = GetComponentInChildren<CircleCollider2D>();
}
void PlaceAsteriods () {
GameObject ASP = new GameObject("Spawner");
bool cannotPlaceThere = true;
for (int a = 0; a < 4 + round; a++) {
ASP.transform.position = new Vector3(Random.Range(SB.leftConstraint, SB.rightConstraint), Random.Range(SB.topConstraint, SB.bottomConstraint));
while(cannotPlaceThere) {
if (triggeredTag != Tags.spawnPos)
cannotPlaceThere = false;
}
Instantiate (bigAsteriods[Random.Range(0, bigAsteriods.Length)], ASP.transform.position , ASP.transform.rotation);
}
Destroy(ASP);
}
void OnTriggerEnter2D(Collider2D hit) {
triggeredTag = hit.collider.tag;
Debug.Log(hit.collider);
}
Anyone have an idea on how to not spawn a rock in the circle collider?
Answer by Reeceg · Jul 18, 2014 at 04:08 AM
you could make a script that destroys the asteroid the second it hits the collider
function OnCollisionEnter(col: Collision){
if (col.gameObject.CompareTag("asteroid")){
Destroy(col.gameObject);
}
}
Answer by Kiwasi · Jul 18, 2014 at 04:13 AM
You have an infinite while loop. Nothing inside your while loop will change the value of triggeredTag, so it will run for ever. Note that the OnTriggerXXX methods are not called during an update method.
Here is how I would structure it
Pick a random position
Check if your random position is inside your collider (use a ray cast?). If not then start over
Spawn the asteroid
Your answer
![](https://koobas.hobune.stream/wayback/20220613154355im_/https://answers.unity.com/themes/thub/images/avi.jpg)