- Home /
Access array from one object to another.
I am currently working on an audio manager that has an array of sounds and methods to play the sounds and create audio sources for them. I have created the Sound "droppedObject" in the editor on an "Audio Manager" object that contains the "AudioManager" script, however I am unable to reference any of the array. Is there a way to do this in Unity? Just want to be able to pass the sound into CreateAudioSource().
public class AudioManager : MonoBehaviour
{
public Sound[] sounds;
public Sound[] locationSounds;
public void CreateAudioSource(Sound s, GameObject g)
{
if(s.source == null)
{
s.source = g.AddComponent<AudioSource>();
s.source.outputAudioMixerGroup = s.outputMixerGroup;
s.source.clip = s.audioClip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
}
public class MainMenuButtons : MonoBehaviour
{
//public Sound droppedObject;
private void Awake()
{
AudioManager audioManager = FindObjectOfType<AudioManager>();
audioManager.CreateAudioSource(droppedObject,gameObject);
}
}
Answer by rudeoff · Feb 19, 2019 at 11:25 PM
It looks like I was able to get around the issue by not referencing the array at all and changing the method.
public void CreateAudioSource(string name, GameObject g)
{
Sound s = Array.Find(locationSounds, sound => sound.name == name);
if(s.source == null)
{
s.source = g.AddComponent<AudioSource>();
s.source.outputAudioMixerGroup = s.outputMixerGroup;
s.source.clip = s.audioClip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
s.source.Play();
}
As a future note "Getting around the issue" isn't an actual solution. That's like saying "$$anonymous$$y car shakes when it goes over 60 miles an hour, so I solved it by just never going over 60 miles an hour."
Your answer

Follow this Question
Related Questions
byte array of image whether can make as the background of unity camera preview 0 Answers
I'm trying to make a conga line of objects. Am I using arrays wrong? 1 Answer
Search an array? 2 Answers
I cant Get the value of an Array 0 Answers
Selecting 2 items from array without selecting the same item twice 1 Answer