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);
}
}
}
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:
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:
playSound is a static method in your class, but you are referring to members like
audioSounds
orminTime
which are not declaredstatic
so they would require aSoundManager sm = new SoundManager();
to operate assm.audioSounds
orsm.minTime
respectivelySolution:
You should make your audioSounds and minTime members static:
But I would consider using singleton objects instead of static members instead:
Make your
audioSounds
andminTime
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:
Static keyword in c#
I'm guessing you get the error on accessing
audioSounds
andminTime
, right?The problem is you can't access
instance members
fromstatic 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 it's 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
andminTime
static, or you could make your method an instance method, if your design permits it.