- Home /
Spawn multiple enemies in relation to gameobject [SOLVED]
I'm currently working on a game with an enemy that can spawn smaller minions. So what I need is to have a few lines that spawn 4 enemies in relation to the gameobject that is spawning them. So when the enemy spawns the new enemies, there is one above, one to the right, one below and one to the left.
Unity 2D C# btw
metalted has solved this question.
Answer by metalted · Mar 19, 2020 at 05:49 PM
So there are endless ways to do this, so ill just show you a couple, then you can see which one you prefer:
/*BASIC*/
public GameObject minion;
public float spawnDistance = 1f;
//Left minion
Instantiate(minion, new Vector3(transform.position.x - spawnDistance, transform.position.y, transform.position.z), Quaternion.identity);
//Top minion
Instantiate(minion, new Vector3(transform.position.x, transform.position.y + spawnDistance, transform.position.z), Quaternion.identity);
//Right minion
Instantiate(minion, new Vector3(transform.position.x + spawnDistance, transform.position.y, transform.position.z), Quaternion.identity);
//Bottom minion
Instantiate(minion, new Vector3(transform.position.x, transform.position.y - spawnDistance, transform.position.z), Quaternion.identity);
/*SIMPLE LOOP*/
Vector3[] directions = new Vector3[]{-Vector3.Right, Vector3.Up, Vector3.Right, -Vector3.Up};
for(int i = 0; i < 4; i++){
Instantiate(minion, transform.position + directions[i] * spawnDistance, Quaternion.identity);
}
/*Calculate the positions with a variable amount of minions:*/
int minionAmount = 4;
//Calculate the radians to rotate when instantiating a new minion.
float anglePerMinion = Mathf.PI * 2 / minionAmount;
//The angle to start from (in degrees/0 is right)
float startingAngle = 0;
//Loop to create all the minions:
for(int i = 0; i < minionAmount; i++){
Vector3 minionPosition = new Vector3(Mathf.Cos((startingAngle * Mathf.Deg2Rad) + anglePerMinion * i) * spawnDistance, Mathf.Sin((startingAngle * Mathf.Deg2Rad) + anglePerMinion * i) * spawnDistance, 0);
Instantiate(minion, minionPosition, Quaternion.identity);
}
If your spawning script is not attached to the enemy itself but to another script, you can just change the transform.position to the right variable, like enemy.transform.position for instance.
This is untested code btw, i dont have a version of unity atm.
Could you set the answer i gave as the accepted answer so the question can be closed? Thanks!