I'm having this error come up and I'm not sure why... I've tried to look it up, people are saying to create an object of the class or create the methods as static... but I'm unsure how.
Here's my code below:
public class SoundManager : MonoBehaviour {
public List<AudioSource> audioSounds = new List<AudioSource>();
public double minTime = 0.5;
public static void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
{
bool playsound = false;
foreach (AudioSource sound in audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= minTime)
{
playsound = true;
}
}
if(playsound) {
AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
}
}
}
I'm guessing you get the error on accessing audioSounds
and minTime
, right?
The problem is you can't access instance members
from static methods
. What this means is that, a static method is a method that exists only once and can be used by all other objects (if its access modifier permits it).
Instance members, on the other hand, are created for every instance of the object. So if you create ten instances, how would the runtime know out of all these instances, which audioSounds
list it should access?
Like others said, make your audioSounds
and minTime
static, or you could make your method an instance method, if your design permits it.
playSound is a static method in your class, but you are referring to members like audioSounds
or minTime
which are not declared static
so they would require a SoundManager sm = new SoundManager();
to operate as sm.audioSounds
or sm.minTime
respectively
Solution:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
playSound is a static method meaning it exists when the program is loaded. audioSounds and minTime are SoundManager instance variable, meaning they will exist within an instance of SoundManager. You have not created an instance of SoundManager so audioSounds doesn't exist (or it does but you do not have a reference to a SoundManager object to see that).
To solve your problem you can either make audioSounds static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
so they will be created and may be referenced in the same way that PlaySound will be. Alternatively you can create an instance of SoundManager from within your method:
SoundManager soundManager = new SoundManager();
foreach (AudioSource sound in soundManager.audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= soundManager.minTime)
{
playsound = true;
}
}
Source: Stackoverflow.com