I am trying to spawn enemy GameObjects onto pre-defined spawn points. The spawn points are set up as a 3 x 2 grid using a jagged array. When the game starts, it should spawn a random number of enemies (from 1 - 6) using the transform.position of the values within the jagged array, but it doesn’t seem to be working. Here’s the code of my game manager object (battleManager):
public class battleManager : MonoBehaviour
{
public GameObject[] team1;
public GameObject[] team2;
public GameObject[] enemyUnits = new GameObject[6];
public GameObject team1Grid;
public GameObject team2Grid;
private int numberOfEnemies;
private int chooseEnemy;
private int chooseSpawnRow;
private int chooseSpawnPoint;
void Start()
{
team1Grid.GetComponent<battleGrid>().xStartPos = 57;
team1Grid.GetComponent<battleGrid>().zStartPos = 35;
Instantiate(team1Grid);
team2Grid.GetComponent<battleGrid>().xStartPos = 57;
team2Grid.GetComponent<battleGrid>().zStartPos = 40;
Instantiate(team2Grid);
SpawnEnemies();
}
public void SpawnEnemies()
{
numberOfEnemies = Random.Range(1, 6);
team2 = new GameObject[numberOfEnemies];
for (int i = 0; i < team2.Length; i++)
{
chooseEnemy = Random.Range(0, enemyUnits.Length);
chooseSpawnRow = Random.Range(0, 1);
chooseSpawnPoint = Random.Range(0, 2);
team2 *= Instantiate(enemyUnits[chooseEnemy], team2Grid.GetComponent<battleGrid>().grid[chooseSpawnPoint][chooseSpawnRow].transform.position, Quaternion.identity);*
}
}
}
And here’s the code for the battleGrid object:
public class battleGrid : MonoBehaviour
{
public GameObject spawnPosition;
public int xStartPos; // Where the grid begins
public int zStartPos; // Where the grid begins
public float xSpace = 3; // Spacing between spawn point tiles
public float zSpace = 2; // Spacing between spawn point tiles
static int rowLength = 3;
public GameObject[] frontRow = new GameObject[rowLength];
public GameObject[] backRow = new GameObject[rowLength];
public GameObject[][] grid = new GameObject[2][];
void Start()
{
for (int i = 0; i < frontRow.Length; i++)
{
frontRow = spawnPosition;
}
for (int i = 0; i < backRow.Length; i++)
{
backRow = spawnPosition;
}
grid[0] = frontRow;
grid[1] = backRow;
for (int i = 0; i < frontRow.Length; i++)
{
for (int j = 0; j < grid.Length; j++)
{
grid[j] = Instantiate(grid[j], new Vector3(xStartPos + (xSpace * i), 0, zStartPos + (zSpace * j)), Quaternion.identity);
Debug.Log(grid[j].transform.position);
}
}
}
In the first script (battleManager), I can’t instantiate using the transform.position of the jagged array elements (“grid[][]”). However each element does seem to have a transform.position value when instantiated in the battleGrid object as I use Debug.Log to verify.
Can someone clarify how I can access the transform.position values of jagged array elements to instantiate Game Objects? Thank you