- Home /
              This question was 
             closed Apr 15, 2016 at 09:00 PM by 
             CodewithFin for the following reason: 
             
 
            The question is answered, right answer was accepted
 
               Question by 
               CodewithFin · Apr 15, 2016 at 12:39 AM · 
                c#unity 5gameobjectsceneaudiosource  
              
 
              Calling an Audio Source on one game object from a script on another game object..?
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?
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by TBruce · Apr 15, 2016 at 12:53 AM
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.");
         }
     }
 }
 
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                