Enemies not spawning in defined annulus

Hi everyone!

I’ve just started using Unity this weekend, so my apologies if I’m asking a stupid question!

I’m trying to spawn waves of enemies within an annulus centered around a random player in my scene and between a min and max distance.

The code works well if the player has moved before the 1st wave is spawned, but if the player hasn’t moved, it looks like the minimum distance from the player is ignored, and enemies spawn almost on the player…

Here’s my function to instantiate waves of enemies:

    public async void InstantiateEnemyWave(GameObject enemyPrefab, int numberOfEnemies, float minDistanceFromPlayer, float maxDistanceFromPlayer)
    {  
        //Find all players
        playerList = Utilities.FindAllPlayers();

        //Pick a random player
        playerPickedRandomly = playerList[Random.Range(0,playerList.Length-1)];

        //Find the x and z coordinates of the player
        Vector2 playerPos = new Vector2(playerPickedRandomly.transform.position.x,playerPickedRandomly.transform.position.z);

        //Create an annulus centered on the player's position and between a minimum and maximum distance   
        pointInSpawnArea = Utilities.RandomPointInAnnulus(playerPos,minDistanceFromPlayer,maxDistanceFromPlayer);

        //Transform the 2D position on the annulus into a 3D position
        spawnPos = new Vector3(pointInSpawnArea.x,1f,pointInSpawnArea.y);

        //Instantiate enemies at the  spawn position
        for (int i = 0; i < numberOfEnemies; i++)
        {
            //avoid overlap of enemies at spawn
            while(Physics.CheckSphere(spawnPos,0.75f))
            {
                spawnPos.x += Random.Range(-1f,1f);
                spawnPos.y = 1f;
                spawnPos.z += Random.Range(-1f,1f);
            }
            PhotonNetwork.InstantiateRoomObject(enemyPrefab.name,spawnPos,Quaternion.identity);
        }  
    }

The function I’m using to create the annulus and return a random point on it is the following:

    public static Vector2 RandomPointInAnnulus(Vector2 origin, float minRadius, float maxRadius)
    {
        var randomDirection = (Random.insideUnitCircle * origin).normalized;
        var randomDistance = Random.Range(minRadius, maxRadius);
        var point = origin + randomDirection * randomDistance;

        return point;
    }

Does anyone know what I’m doing wrong?

Thanks!

You probably want to strip this down to the simplest setup you can imagine, then start debugging some actual values and code flow.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • values in the code you take for granted are actually some other value
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

https://discussions.unity.com/t/839300/3

You must find a way to get the information you need in order to reason about what the problem is.

Thanks for the tips!

After putting some Debug.Log() lines a bit everywhere, I managed to find that the problem was located in RandomPointInAnnulus():

var randomDirection = (Random.insideUnitCircle * origin).normalized;

Since I was using the position of the player as “origin”, Random.insideUnitCircle * origin was returning a (0,0) Vector2 if the player hadn’t moved (and was at the (0,0) position in the world).

1 Like