Search Unity

C# NullReferenceException Error

Discussion in 'Scripting' started by jpalmer999, May 17, 2019.

  1. jpalmer999

    jpalmer999

    Joined:
    Apr 17, 2014
    Posts:
    9
    So I am trying to create an audio options menu however it is coming up with the following error:

    NullReferenceException: Object reference not set to an instance of an object
    AudioOptions_Master.Start () (at Assets/Scripts/UI/Standard Menus/Options Menu/Sound/AudioOptions_Master.cs:26)

    However, everything is assigned in the inspector.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class AudioOptions_Master : MonoBehaviour
    7. {
    8.     public Button BTN_MuteMaster;
    9.     public Button BTN_TestMaster;
    10.  
    11.     public Color Color_BTN_Sound;
    12.     public Color Color_BTN_Muted;
    13.     public Color Color_TXT_Sound;
    14.     public Color Color_TXT_Muted;
    15.  
    16.     public float FLT_Master;
    17.     public float FLT_MasterBackup;
    18.  
    19.     public Slider SLI_Master;
    20.  
    21.     public Text TXT_Master;
    22.     public Text TXT_BTN_MuteMaster;
    23.  
    24.     public void Start ( )
    25.     {
    26.         BTN_MuteMaster.onClick.AddListener ( Mute_Master );
    27.     }
    28.  
    29.     public void Mute_Master ( )
    30.     {
    31.         if ( FLT_Master == 0.0f )
    32.         {
    33.             // Restore Backup
    34.             FLT_Master = FLT_MasterBackup;
    35.  
    36.             // Change Color
    37.             BTN_MuteMaster.GetComponent<UnityEngine.UI.Image> ( ).color = Color_BTN_Sound;
    38.         }
    39.  
    40.         else
    41.         {
    42.             // Set Backup
    43.             FLT_MasterBackup = FLT_Master;
    44.  
    45.             // Mute Master Audio
    46.             FLT_Master = 0.0f;
    47.  
    48.             // Change Color
    49.             BTN_MuteMaster.GetComponent<UnityEngine.UI.Image> ( ).color = Color_BTN_Muted;
    50.         }
    51.     }
    52. }
    53.  
     
  2. Shinyclef

    Shinyclef

    Joined:
    Nov 20, 2013
    Posts:
    505
    Surely, BTN_MuteMaster must be null...
    Put a break point on line 26 and inspect.
    Alternatively just put:
    Debug.Log("Is it null? " + (BTN_MuteMaster == null));
    before it.
     
  3. jpalmer999

    jpalmer999

    Joined:
    Apr 17, 2014
    Posts:
    9
    Ah found the problem. it was simply a case of having the script on the button as well as the audio handler object I made. Thanks for the help though :)