hey guys, maybe can someone help me with a code… I’m a fresh newbie to unity. I have a problem with the spawner I created I tried to figure out how to tell the spawner NOT to spawn over other “aliens” existing colliders, if the random position is already occupied by another alien collider, then spawn somewhere else within the range.
tried to understand Physics2D.OverlapCircle but I couldn’t make it work within my code…
well, after the spawn animation there is a new object created but the animation object and the object created after the animation ends share the same tag.
this is the code currently running in the example video:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlienSpawner : MonoBehaviour
{
public GameObject AlienSpawnAnimation;
private int respawnTime;
private int start = 1;
void Start()
{
StartCoroutine(alienWave());
}
void Update()
{
respawnTime = RandomRespawnTime();
}
private void spawnAlien()
{
Instantiate(AlienSpawnAnimation, new Vector3(Random.Range(-4.18f, 4.18f), Random.Range(3.74f, 0.35f), 0),transform.rotation = Quaternion.identity);
}
IEnumerator alienWave()
{
while(true)
{
if(start == 1)
{
yield return new WaitForSeconds(1);
spawnAlien();
start--;
}
else
{
yield return new WaitForSeconds(1);
spawnAlien();
}
}
}
private int RandomRespawnTime()
{
int a = Random.Range(8, 20);
return a;
}
}
Are you asking for someone to write the code for you because the code doesn’t include any physics query like OverlapCircle. Overlap circle couldn’t be easier: You specify the position of the circle and the radius and it tells you what it overlaps. If you intend to spawn at a position and you have a radius that covers what you want to spawn then you can detect it; what is the specific problem you’re having with OverlapCircle, I can answer that.
If you don’t understand something then posting code and a video isn’t going to help if it doesn’t highlight the actual problem you’re having.
Also, I would always recommend that if you don’t understand something, move away from your project and learn how to use it in a new empty project. Add a collider, try to detect it with the OverlapCircle query. When you understand, come back to your project.
I’m not sure why you’re doing the following either. Why would you set the transform of the spawner? Typically you’d just pass “Quaternion.identity” to mean no rotation.
You don’t compare a collider against true/false, it’s not a bool type. It’ll either be NULL or a reference to a collider.
The above code doesn’t “crash”, it’ll likely enter the infinite loop you’ve created and therefore lock the main-thread and never exit. If you don’t find anything then you instantiate something but then continue in the while loop forever. Just follow the logic in your head.