I’m trying to make a shoot’em up, galaga-clone type game because it seemed like a simple enough starting point after the unity tutorial courses, but am running into trouble when switching out gun patterns.
Here is the code handling the firing action:
isShooting = Input.GetKeyDown(KeyCode.Space);
if (isShooting)
{
foreach(Gun gun in guns)
{
gun.Shoot();
}
}
Which works through this code where I instantiate the gun pattern and access the script for each one:
if (Input.GetKeyDown(KeyCode.Alpha2))
{
currentFiringPattern = FiringPattern.Double;
Destroy(currentGuns);
currentGuns = Instantiate(gunsPrefabs[1], this.transform.position + new Vector3(0, 0, .75f),
Quaternion.identity, gameObject.transform);
guns = transform.GetComponentsInChildren<Gun>();
}
It works just fine, let’s me shoot bullets, and fills the array as seen here:
Problem being, even after I clear the array, it starts assigning elements at the end of the array’s previous length, like this:
This causes my code to no longer work, and I can’t shoot bullets anymore because my firing for loop activates starting with the beginning of the array. If there are empty elements at the beginning of the array I get an error for trying to reference a destroyed object.
I tried a few different ways to clear and resize the array:
if (Input.GetKeyDown(KeyCode.C))
{
System.Array.Clear(guns, 0, guns.Length);
System.Array.Resize<Gun>(ref guns, 0);
}
Which I thought worked:
While the first line (Array.Clear) removed all elements, they still showed up in the inspector. It wasn’t until I added the next (Array.Resize) that it actually cleared it to looking like an empty array in the inspector.
Alas, it didn’t help, and next time I press a key to switch gun patterns it assigns the elements to the array after the end of its previous length, leaving me with multiple empty elements at the top.
One thing that does work though, is manually dragging the new elements to the top of the array:
This allowed me to change my gun pattern as much as I wanted and no matter how long the array got, so long as I manually dragged them up in the inspector.
I feel like there’s something simple I’m missing but I also feel like I’ve tried everything over the past couple hours. How can I start over in the array each time I press a key to switch new weapons?





