c# – 访问非静态成员需要一个对象引用

前端之家收集整理的这篇文章主要介绍了c# – 访问非静态成员需要一个对象引用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个错误出现,我不知道为什么…我试图查找,人们说要创建一个类的对象或创建方法作为静态…但我是不确定怎么样

这是我的代码如下:

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);
    }
}
}

解决方法

你应该使你的audioSounds和minTime成员静态:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

但是,我会考虑使用单例对象而不是静态成员:

public class SoundManager : MonoBehavIoUr
{

    public List<AudioSource> audioSounds = new List<AudioSource>();
    public double minTime = 0.5;

    public static SoundManager Instance { get; private set; }

    void Awake()
    {
        Instance = this;
    }

    public void playSound(AudioClip sourceSound,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);
        }

    }
}

猜你在找的C#相关文章