Search Unity

Public AudioMixer assigned in Editor gives NullReference

Discussion in 'Scripting' started by Adsolution, Feb 6, 2016.

  1. Adsolution

    Adsolution

    Joined:
    Oct 27, 2015
    Posts:
    5
    - Originally posted this in Answers, but it's been awaiting moderation for three days now:


    In the following code, I've assigned an Audio Mixer that I created to the masterMixer variable by dragging it in from the Project view to its public variable component in the Inspector:

    However, whenever I try to use GetFloat/SetFloat as seen here, I'm given a NullReferenceException for masterMixer.

    Now, the first thing I thought was that I needed to assign an actual instance of "Audio" in the scene to masterMixer, but there doesn't seem to be any way of actually placing an Audio Mixer in your scene.

    I followed the official tutorial on exposing Audio Mixer parameters, but the only difference is that he's controlling SetFloat/GetFloat entirely through default UI stuff in the Inspector, whereas I'm triggering all changes through code. That shouldn't make a difference, right?

    Code (CSharp):
    1.     using UnityEngine;
    2.     using System.Collections;
    3.     using UnityEngine.Audio;
    4.    
    5.     public class AudioMixerControl : MonoBehaviour {
    6.    
    7.         public AudioMixer masterMixer;
    8.        
    9.         public float GetMusicVolume()
    10.         {
    11.             float vol;
    12.             masterMixer.GetFloat("musicVolume", out vol);
    13.             return vol;
    14.         }
    15.    
    16.         public float GetSoundVolume()
    17.         {
    18.             float vol;
    19.             masterMixer.GetFloat("soundVolume", out vol);
    20.             return vol;
    21.         }
    22.    
    23.    
    24.         public void SetMusicVolume(float vol)
    25.         {
    26.             masterMixer.SetFloat("musicVolume", vol);
    27.         }
    28.    
    29.         public void SetSoundVolume(float vol)
    30.         {
    31.             masterMixer.SetFloat("soundVolume", vol);
    32.         }
    33.     }
    34.