Algorithm for loading sounds

So I wrote this function to load in a bunch of step sounds in an array of different step materials, inside each step material is a sneak step, walk step and run step sound.

So lets say in one instance

  • i ,in the first loop for materials,
    is 3, which is metal
  • t , in the second loop for step type
    is 1, which is sneak
  • r, in one of the third loops is 4,
    which is the 4th clip
  • The filename would be
    step_sneak_metal4 , and it is if you
    use debug.logs.

And the "Resources.Load(“filename”) as AudioClip
" works everywhere else. and again works according to debug.log and says this is a valid file that exists within the resource folder.

but if you set it equal to steps_.run[r] or steps*.sneak[r] or whatever it says*_
“Null Reference Exception: Object Reference not set to an instance of an object”
but not outside of the function with a similar assignment.

public void load()
{
steps = new StepPack[stepTypes.Length];
for (int i = 0; i < stepTypes.Length; i++)
{
for (int t = 0; t < 3; t++)
{
switch (t)
{
case 0:
for (int r = 0; r < 5; r++) steps.run[r] = Resources.Load(“SFX/player/step/step_run_” + stepTypes + (r + 1).ToString()) as AudioClip;
break;
case 1:
for (int r = 0; r < 5; r++) steps.sneak[r] = Resources.Load(“SFX/player/step/step_sneak_” + stepTypes + (r + 1).ToString()) as AudioClip;
break;
case 2:
for (int r = 0; r < 5; r++) steps.walk[r] = Resources.Load(“SFX/player/step/step_walk_” + stepTypes + (r + 1).ToString()) as AudioClip;
break;
}
}
}

What is “StepPack”? I guess it’s a custom class. You never create any instances of that class.

This:

steps = new StepPack[stepTypes.Length];

only creates an array but each element in that array defaults to “null”. Further more you have to ensure that your nested arrays (run, sneak, walk) are initialized as well inside the StepPack class.

Also using a switch case like this makes no sense and is bad practise. Each loop iteration only one case will be processed. So you can just scrap that whole for loop and just execute those 3 steps one after another.

So something like this:

steps = new StepPack[stepTypes.Length];
for (int i = 0; i < stepTypes.Length; i++)
{
    // creating an actual instance of your StepPack class
    steps *= new StepPack();*

string path = “SFX/player/step/step_”;
string type = stepTypes*;*
for (int r = 0; r < 5; r++)
{
steps*.run[r] = Resources.Load(path+“run_” + type + (r + 1));
steps.sneak[r] = Resources.Load(path+“sneak_” + type + (r + 1));
steps.walk[r] = Resources.Load(path+“walk_” + type + (r + 1));
_}
}*

You may want to use a format string instead and use string.Format to replace the different parts._