0

I am currently creating a game where the player is on a square platform and I want the enemies to spawn randomly from the four edges of the platform. So far I am able to make my enemies spawn randomly from one edge, but don't know how to make them spawn from all four. I imagine it would work with a Vector3 array? But I am struggling to get this right. Please help!

My spawn code so far:

void SpawnRandomEnemy()
    {
        if(!playerControllerScript.gameOver && !playerControllerScript.hasFreezePowerup)
        {
            int enemyIndex = Random.Range(0, enemyPrefabs.Length);
            Vector3 spawnPos = new Vector3(Random.Range(-spawnRange, spawnRange), 0, spawnPosZ);

            Instantiate(enemyPrefabs[enemyIndex], spawnPos, enemyPrefabs[enemyIndex].transform.rotation);
        }        
    }

1 Answers1

0

The easiest thing you could go for is placing 4 empty gameobjects to serve as spawners at each of the 4 sides of the square. Place them in an array consisting of gameobjects (similar to what you've done with the enemyPrefabs array).

Then you would pick 1 of them randomly just like picking the enemy index:

int spawnIndex = Random.Range(0, spawnPoints.Length);

Then you could take the position of that spawn point.

Vector3 spawnPos = spawnPoints[spawnIndex].transform.position;

Then you can edit that spawn position in many ways you would like. For example, you can set Y to be equal to 0 (or whatever fits your needs), you can add some offset to the X position of the gameobject (so that they do not spawn everytime at the same position). You can basically do that for either X, Y, Z - you just have to play around with it until it really starts acting as a randomly set spawner (just be careful with the offsets so that your enemies do not spawn out of the square).

spawnPos.X = spawnPos.X + someOffset;

You will have to generate the offset randomly, too - just like the things above.

Chochosan
  • 156
  • 5
  • That makes sense, thank you! I'm super new to C# and Unity so often times I find myself struggling with the simplest things! So thank you for your helpful answer! – FloodAndBones Nov 18 '19 at 21:04