简体   繁体   中英

How to create a random spawner in unity 2d?

I am making a game in Unity2D i which you have to match the correct projectiles with the enemies but I can't randomly spawn them, it just spawns one... (btw this is my first game)

   {
       timeBTWSpawn = StartTimeBTWSpawn;

       private void Update()
   {

       if(timeBTWSpawn <= 0 )
       {
           rand = Random.Range(0, enemies.Length);
           Instantiate(enemies[0], SpawnPoint.transform.position, Quaternion.identity);```
           timeBTWSpawn = StartTimeBTWSpawn;
       }
       else
       {
           timeBTWSpawn -= Time.deltaTime;
       }
   }
}

i expect 3 different enemies to be randomly spawned but it only spawns the first one in the array.

there is one minor mistake. You are not actually using "rand" variable inside the instantiate method. having 0 in the index will always spawn the first element inside enemies array.it should be like this:

Code:

       Instantiate(enemies[rand], SpawnPoint.transform.position, Quaternion.identity);

this will fix:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM