0
\$\begingroup\$

I have a question regarding spawning an array of GameObjects in Unity. What I want to happen is that when a big enemy dies, it will spawn enemies into their respective Transform positions (i.e., Enemy 1 will spawn in Position 1, Enemy 2 in position 2, and so on).

I suppose I could go on with something like:

// C#

public GameObject[] Enemies;
public Transform[] SpawnPoints;

void KillEnemy()
{
    GameObject enemy1 = Instantiate(Enemies[0], SpawnPoints[0].position, SpawnPoints[0].rotation;
    GameObject enemy2 = Instantiate(Enemies[1], SpawnPoints[1].position, SpawnPoints[1].rotation;
    GameObject enemy3 = Instantiate(Enemies[2], SpawnPoints[2].position, SpawnPoints[2].rotation;

    Destroy(gameObject)
}

But the problems are:
1. I'm aware that the code is expensive to run, especially since I'm doing a 2D game; and
2. It provides no flexibility, meaning if I want a different enemy to use the same code, then I won't be able to do stuff like adding more enemies to spawn (after the first one dies, of course).

So yeah, I hope I get some help with this. Thanks!

\$\endgroup\$
4
  • \$\begingroup\$ Are you looking for a for loop? \$\endgroup\$
    – DMGregory
    Commented Oct 3, 2019 at 10:45
  • \$\begingroup\$ Could you edit to describe more what flexibility you're looking for exactly? What sorts of scenarios would you want this code to handle that it doesn't right now? \$\endgroup\$
    – Anko
    Commented Oct 3, 2019 at 11:02
  • \$\begingroup\$ @DMGregory I was thinking of a for loop but I'm not sure how to implement it. Anyway, I might as well give it a try! \$\endgroup\$ Commented Oct 3, 2019 at 11:29
  • \$\begingroup\$ @Anko I think I used flexibility quite loosely here. What I mean to say is that if I add one more object (and a corresponding transform), then naturally it will affect every enemy that uses the same code. (I hope you get it lol) \$\endgroup\$ Commented Oct 3, 2019 at 11:32

1 Answer 1

2
\$\begingroup\$

Would simple for loop work?

public GameObject[] Enemies;
public Transform[] SpawnPoints;

void KillEnemy()
{
    for(var i; i < Enemies.Length; i++) {
        var spawnPoint = SpawnPoints.Length> i ? SpawnPoints[i] : SpawnPoints[SpawnPoints.Length- 1];
        Instantiate(Enemies[i], spawnPoint.position, spawnPoint.rotation)
    }

    Destroy(gameObject)
}

And if you need the reference to the created enemy just do var enemy = Instantiate... etc.

\$\endgroup\$
1
  • \$\begingroup\$ Yup! This worked man! Thanks a lot! \$\endgroup\$ Commented Oct 3, 2019 at 11:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .