- Home /
How to Play a Sound from an Array from an Overloaded Method?
I have
public AudioClip[] toPlay;
We call:
playMySound(toPlay);
The method:
public void playMySound (AudioClip sound){
for(int i = 0; i < soundSource.Length; i++) {
soundSource[i].audio.clip = sound;
soundSource[i].audio.Play();
}
}
I get the following errors:
error CS1502: The best overloaded method match for myAudioScript.PlaySound(UnityEngine.AudioClip)' has some invalid arguments** **error CS1503: Argument
#1' cannot convert UnityEngine.AudioClip[]' expression to type
UnityEngine.AudioClip'
If I have:
public AudioClip song;
There aren't any errors and it works fine, but obviously I cannot have an array.
Please help me to understand this better.
What is the proper syntax for this?
Thank in advance.
Answer by Fmressel · Oct 15, 2014 at 03:18 AM
I think your problem is that you are calling playMySound with an AudioClip array when playMySound only takes a single AudioClip. This is why when you change "song" to be "public AudioClip" instead of "public AudioClip[]" it works.
So, in order to fix your code to work with an array, you need to do the following:
public AudioClip[] toPlay;
//Since toPlay is of type AudioClip array and the variable needed by playMySound is of type
//AudioClip you need to choose which AudioClip in your array you want to pass to playMySound
//you do this by the below method
playMySound(toPlay[0]);
//The number can be any size as long as it corresponds to an object in your array and should never exceed the length of the array itself
//Also remember that arrays count up from 0 so the first object in your array will be number 0
public void playMySound (AudioClip sound){
for(int i = 0; i < soundSource.Length; i++) {
soundSource[i].audio.clip = sound;
soundSource[i].audio.Play();
}
}
More info on arrays can be found here:
http://docs.unity3d.com/ScriptReference/Array.html
Hope that helps! If this didn't answer your question, please let me know!
Yeah that's it, I totally get it now. Thanks for your excellent explanation and response.
Your answer
Follow this Question
Related Questions
Can not play a disabled audio source persistent problem 0 Answers
loop animation while audio is playing 0 Answers
Cant repeat Sound 1 Answer
Play Animation if Sound Output 0 Answers
Sound Timing 1 Answer