I have two scripts that handle sounds. One is an AudioManager that should play the sounds I want, Another is a"Sounds" class which handles each sound for itself.
It works great with one AudioClip, However, I’d like to make the AudioClips in the Sounds class as Arrays(or lists?) and I am having trouble making it work.
I get an index out of range.
Here is the Sounds class:
using System.Collections.Generic;
using UnityEngine.Audio;
using UnityEngine;
[System.Serializable]
public class Sounds
{
public string name;
public AudioClip[] audioClip;
[Range(0f, 1f)]
public float volume;
[Range(0f, 1f)]
public float pitch;
public bool loop;
public AudioMixerGroup audioMixerGroup;
[HideInInspector]
public AudioSource audioSource;
}
here is the AudioManager Script:
using System;
using System.Collections.Generic;
using UnityEngine.Audio;
using UnityEngine;
using Random = System.Random;
public class AudioManagerNew : MonoBehaviour
{
public Sounds[] sounds;
public static AudioManagerNew instance;
private void Awake()
{
DontDestroyOnLoad(gameObject);
if (instance == null)
{
instance = this;
}
else
{
Destroy(gameObject);
return;
}
foreach (var s in sounds)
{
s.audioSource = gameObject.AddComponent<AudioSource>();
s.audioSource.clip = s.audioClip[UnityEngine.Random.Range(0, s.audioClip.Length)];
s.audioSource.volume = s.volume;
s.audioSource.pitch = s.pitch;
s.audioSource.outputAudioMixerGroup = s.audioMixerGroup;
s.audioSource.loop = s.loop;
}
}
public void PlaySound(string name)
{
Sounds s = Array.Find(sounds, sound => sound.name == name);
s.audioSource.Play();
if (s == null)
{
Debug.LogWarning("Sound" + name + "not found");
return;
}
}
//How to play sounds from other scripts:
// FindObjectOfType<AudioManager>().Play("string of clip name");
}
I’m clearly not writing the array the correct way, how can I make the audio manager recognize the AudioClip array?