I want to call an Audio Source in a game object from a script in a different game object in a different scene… How would I do that?
Here is a code example with the AudioSource component
using UnityEngine;
using System.Collections;
public class MyClass1 : MonoBehaviour
{
[HideInInspector] // remove this line if it is intended to have the AudioSource visible in the inspector
public AudioSource audioSource;
void Start()
{
if (audioSource == null)
{ // if AudioSource is missing
Debug.LogWarning("AudioSource component missing from this gameobject. Adding one.");
// let's just add the AudioSource component dynamically
audioSource = gameObject.AddComponent<AudioSource>();
}
}
}
Here is a code example that gets the AudioSource component from MyClass1
using UnityEngine;
using System.Collections;
public class MyClass2 : MonoBehaviour
{
public MyClass1 myClass1;
private AudioSource audioSource;
void Start()
{
if (myClass1 == null)
{ // if AudioSource is missing
Debug.LogWarning("MyClass1 component missing from this gameobject.");
}
else if (myClass1.GetComponent<AudioSource>() != null)
{
audioSource = myClass1.GetComponent<AudioSource>();
}
else
{ // we suld never enter this block
Debug.LogWarning("MyClass1 doe not have an AudioSource component.");
}
}
}