Hi guys, gals and anybody else who might be here,
I have this code, that is attached as a script to a child object of an enemy in my top-down vertically-scrolling shooter:
public GameObject[] firePatterns;
public int fireDelayInFrames;
public bool isFinishedFiring;
private int frameControl = 0;
private int fireControl = 0;
private void Update()
{
if (GetComponentInParent<EnemyShooter>().readyToFire)
{
frameControl++;
if ((frameControl % fireDelayInFrames) == 0)
{
if (fireControl > firePatterns.Length)
{
isFinishedFiring = true;
}
else
{
Instantiate(firePatterns[fireControl], transform.position, transform.rotation);
Debug.Log("Emitter Script: Should fire here.");
fireControl++;
}
frameControl = 0;
}
}
}
It works fine up until the last object in the array is instantiated, at which point it throws an IndexOutOfRangeException, of course pointing to the line with the Instantiate() method on it. I know that this Exception is only called when the integer used to refer to an array’s index lies beyond the scope of that index, but my if checks should stop this from happening.
Additionally, and also possibly more important to find out the cause of, the code snippet above also randomly causes MissingReferenceExceptions,once again on the line with the Instantiate() method, to be thrown when the script is run.
I would also like to improve upon this script, perhaps by constructing it as a coroutine and calling it from the instead of calling it once every frame in the Update() method. However, i am somewhat lackluster in skill when it comes to coroutines.
Could one of you fine people provide me with some advice/help on what is happening with my code snippet, and also provide insight as to how I could restructure this as a coroutine instead?