• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by mats1105 · Dec 31, 2018 at 01:20 AM · nullreferenceexceptionaudiosource

Audio Source is null when changing scene

Hi, I am new to c# and unity.

I am having an issue where I have an array of audio sources stored on an AudioManager that has "Don't destroy on load".

All the sounds work as intended until I switch scene. Then most of the Audio sources give me an NRE when I call them from other scripts. When I switch back to the starting scene it's back to normal.


I have researched for almost 6 hours now and have found several similar problems, but no solution that either worked or I understood. I do believe that the sound that plays when my character is running is the source of the problem. (but I could be wrong)


I am also testing if Sound s == null and returning if it is, but seems to not do anything


The error I am getting is:

NullReferenceException AudioManager.isPlaying (System.String name) (at Assets/Scripts/AudioManager.cs:65) RunningSound.Update () (at Assets/Scripts/RunningSound.cs:38)

The lines 38 and 65 will be marked in the code down bellow.


Here is the AudioManager script: [code] public class AudioManager : MonoBehaviour {

 public Sound[] sounds;

 public static AudioManager instance;

 // Use this for initialization
 void Awake () {

     if (instance == null)
         instance = this;
     else
     {
         Destroy(gameObject);
         return;
     }

     DontDestroyOnLoad(gameObject);

     foreach (Sound s in sounds)
     {
         s.source = gameObject.AddComponent<AudioSource>();
         s.source.clip = s.clip;

         s.source.volume = s.volume;
         s.source.pitch = s.pitch;
         s.source.loop = s.loop;
     }
 }

 public void Play (string name)
 {
     Sound s = Array.Find(sounds, sound => sound.name == name);
     if (s == null) //---------------line 38-------------------//
     {
         Debug.Log("Sound: " + name + " not found!");
         return;
     }
     s.source.Play();
 }

 public void Stop (string name)
 {
     Sound s = Array.Find(sounds, sound => sound.name == name);
     if (s == null)
     {
         Debug.Log("Sound: " + name + " not found!");
         return;
     }
     s.source.Stop();
 }

 public bool isPlaying(string name)
 {
     Sound s = Array.Find(sounds, sound => sound.name == name);
     if (s == null) 
     {
         Debug.Log("Sound: " + name + " not found!");
         return false;
     }
     return s.source.isPlaying; //----------line 65-----------//
 }

} [/code]

And here is the RunningSound script that might be an issue:

Might also be an inefficient way of determining if the run sound should be played. (I don't know)

[code] public class RunningSound : MonoBehaviour {

 private bool isRunning = false;
 private bool isGrounded;
 private bool groundedLastFrame = false;

 private float runSpeed;
 private AudioManager audioManager;

 private PhysicsObject physicsObjectScript;

 // Use this for initialization
 void Start () {
     GameObject thePlayer = GameObject.FindWithTag("Player");
     physicsObjectScript = thePlayer.GetComponent<PhysicsObject>();
     audioManager = FindObjectOfType<AudioManager>();
 }
 
 // Update is called once per frame
 void Update () {
     isGrounded = physicsObjectScript.grounded;
     runSpeed = Mathf.Abs(Input.GetAxis("Horizontal"));

     //Check if running
     if (runSpeed > 0.01 && isGrounded)
     {
         isRunning = true;
     } else
     {
         isRunning = false;
     }

     //check if run sound is playing
     bool isPlayingRun = audioManager.isPlaying("Run");

     if (isRunning)
     {
         if (!isPlayingRun)
         {
             audioManager.Play("Run");
         }
     }
     else
     {
         if (isPlayingRun)
         {
             audioManager.Stop("Run");
         }
     }

     if (isGrounded && !groundedLastFrame)
     {
         bool isPlayingLand = audioManager.isPlaying("Land");
         bool isPlayingJump = audioManager.isPlaying("Jump");
         //play landing sound
         if (!isPlayingJump && !isPlayingLand)
         {
             audioManager.Play("Land");
         }
     }
     groundedLastFrame = isGrounded;
 }

} [/code]

And lastly the Sound Class I used as template to store the sounds:

[code] [System.Serializable] public class Sound {

 public string name;

 public AudioClip clip;

 [Range(0f, 1f)]
 public float volume;
 [Range(0f, 3f)]
 public float pitch;

 public bool loop;

 [HideInInspector]
 public AudioSource source;

} [/code]


Thanks in advance for any replies. Hopefully I can walk away with a little moe understanding of how all this works.

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image hexagonius · Dec 31, 2018 at 09:52 AM 0
Share

what is Sound? it's neither AudioClip nor AudioSource.

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by c_Feng · Dec 31, 2018 at 06:41 PM

@mats1105

Your problem is the way you're referencing the AudioManager. "FindObjectOfType" only works with objects in the same scene. DoNotDestroyOnLoad places those objects in a separate, persistent scene.

What you need to do to reference your AudioManager, instead, is to take advantage of the static instance you made. By nature of it being static, you can globally reference your AudioManager by calling "AudioManager.instance". In the RunningSound script, you can either cache AudioManager as you are already doing with the following line:

 audioManager = AudioManager.instance;

or simply remove the variable altogether and use "AudioManager.instance" without any performance hits.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mats1105 · Dec 31, 2018 at 07:57 PM 0
Share

Thanks for explaining! This seams really promising. Will try out tomorrow.

avatar image Vivien_Lynn · Apr 29, 2020 at 04:09 PM 0
Share

Very helpful and useful explanation! Thank you I would recommend to put audio$$anonymous$$anager = Audio$$anonymous$$anager.instance; into the Start-Function, and not Awake. That fixed it for me.

avatar image
0

Answer by meMUmar · Dec 31, 2018 at 10:09 AM

Hi.. Maybe it is due to that you didn't have placed the AudioManager Script in other scene.... You must have to place the script containing sound in other scene and must have AudioSource to play these sound. Hope it will work..

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image mats1105 · Dec 31, 2018 at 10:49 AM 1
Share

The Audio$$anonymous$$anager is in every scene and workes perfectly in every scene when the game starts from that scene.

I did however try to build my game, and when I ran it outside of unity everything worked fine, even switching scenes.

EDIT: But would be nice to get it working in unity also..

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

103 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

NullReferenceException When Attempting To Play AudioClips 1 Answer

Beginners troubles with audiosource 0 Answers

Destroy object last on application close. 1 Answer

Initialize UnityEvent via script 1 Answer

Unity null check 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges