- Home /
 
 
               Question by 
               dieterweireldt · Oct 01, 2016 at 06:55 AM · 
                audionullreferenceexceptionaudiosourceaudioclip  
              
 
              Beginners troubles with audiosource
I'm still new to learning Unity and seem to have a problem.. I would like to change an audiosource's clip depending on the button that is pressed and play it.. it works when I use
 public void onPlaySound()
     {
        AudioSource WhateverSound = GetComponent<AudioSource>();
         WhateverSound.Play();
     }
 
               but when I want to extend the scope of AudioSource so every function can access it I keep getting "is never assigned and will always have a value of null" and "nullreferenceException"..
I used the Unity Scripting documentation and tried:
 public class ExampleClass : MonoBehaviour {
     public AudioClip impact;
     AudioSource WhateverSound;
     
     void Start() {
         WhateverSound= GetComponent<AudioSource>();
     }
     
     void OnPlaySound() {
         WhateverSound.PlayOneShot(impact, 0.7F);
     }
 }
 
               but I keep getting those errors.. I checked google and if found I needed to use the "new" keyword like
 AudioSource WhateverSound = new AudioSource();
 
               but didn't work either..
I'm sure it's a stupid mistake, but I can't figure it out..
               Comment
              
 
               
              Your answer