Array = null when passing as parameter
Straight to the point. The following code is in a script that executes before all other scripts:
public static AudioClip[] FootstepSounds;
void Start()
{
FootstepSounds = Resources.LoadAll("Sound Library/Footstep Sounds", typeof(AudioClip)) as AudioClip[];
}
The above always worked for me and the path is correct. I then use this Array in another script like this:
AudioClip currentAudioClip;
void Footstep() // I'm using this as a Mecanim Event on a walk animation
{
Debug.Log("List null? -> " + SourceScript.FootstepSounds == null); // returns "List null? -> false"
Debug.Log("List length -> " + SourceScript.FootstepSounds.Length); // NullReferenceException
// of course NullReferenceException at the following line too
currentAudioClip = SourceScript.FootstepSounds[Random.Range(0, SourceScript.FootstepSounds.Length)];
}
The compiler tells me that the collection is not null, so it must be the elements, which were obviously provided inside the source script. Does anyone know what's going on?
Are you positive the Start() is being run first? I'd suggest adding a Debug.Log() to confirm. I don't know $$anonymous$$ecanim, so if it's being triggered like an Awake(), it'll run before any Start() even if script order is set. You can move the Resources.LoadAll() to Awake and try it there as well.
Also, are you sure the Debug.Log in Footstep() is actually returning "List null? -> false"? When I run this line I get simply "False" due to order of operations. It's running the + operator first, then doing the equality check, so it's comparing a string to null. Try running it this way to confirm order of operations:
Debug.Log("List null? -> " + (SourceScript.FootstepSounds == null) );
Answer by betaFlux · Dec 19, 2015 at 07:54 PM
Thanks for your suggestions, OncaLupe. It's weird but it looks like the only way to make it work, is to replace all 'AudioClip' occurrences with 'object' and cast to 'AudioClip' in the final assignment at line 8 in the second script.
Your answer

Follow this Question
Related Questions
Not sure why i'm getting NullReferenceException 0 Answers
NullReferenceException when changing Canvas text via code 0 Answers
NullReferenceException: Object reference not set to an instance of an object error ? 1 Answer
Help with my PopUp Damage Text! 0 Answers
A problem "NullReferenceException: Object reference not set to an instance of an object(...)" 0 Answers