Hi, I am making a game where I instantiate the players units at the start of each round (yes perhaps it should be pooled). Issue is that I would like for the player to be able to change the order of when units spawn in game. There will be 20 or more available units, so I need a manageable way to do it. Perhaps it could be done with a list system, though I am stuck on how more precisely that would be done.
Thanks in advance for any help.
public void EnterBattleStart()
{
for (int i = 0; i < elvenWarriors; i++)
{
Instantiate(elvenWarriorPlayer, playerSpawnPosition, Quaternion.identity);
playerSpawnPosition -= new Vector3(0, 1);
}
for (int i = 0; i < dwarvenWarriors; i++)
{
Instantiate(dwarfWarriorPlayer, playerSpawnPosition, Quaternion.identity);
playerSpawnPosition -= new Vector3(0, 1);
}
for (int i = 0; i < adventurers; i++)
{
Instantiate(adventurerPlayer, playerSpawnPosition, Quaternion.identity);
playerSpawnPosition -= new Vector3(0, 1);
}
}
Is there any particular reason you’re using a for loop to spawn these characters? Just curious because I would probably use a list to do this as well, you could use an integer or grab the index in the list to spawn what you want.
Hi, have a look at the command pattern, Charles from Infallible Code did a great video on the subject recently :
Instead of directly calling your spawning logic, you embed it cleanly in a command object with all the data you need like which amount of enemies and which type so that it can perform the spawning.
Then you setup your UI to let your player configure his spawns and you generate the list of command object from that.
So I guess I could make a list of gameobjects, and then instantiate the number of units the player has? But I need to instantiate them beneath each other, so will need to increment y -2 each time. Not sure how I could spawn like I do in my loop using a list.
You could create a mini data class and loop through them that way:
[System.Serializable]
public class UnitStack
{
public GameObject spawnPrefab;
public int number;
}
public class StacksSpawner : MonoBehaviour
{
public UnitStack[] unitStacks;
public void Start()
{
Vector3 playerSpawnPosition = Vector3.zero; // Don't know how you populate this, so I'll just start at zero
for(int i = 0; i < unitStacks.length; i++)
{
UnitStack currentStack = unitStacks[i]; // Just for clarity and control, could use foreach instead if you want
for(int j = 0; j < currentStack.number; j++)
{
Instantiate(currentStack.spawnPrefab, playerSpawnPosition, Quaternion.identity);
playerSpawnPosition -= new Vector3(0, 1);
}
}
}
}