Search Unity

Other NullReferenceExceptions when trying to play audio file

Discussion in 'Scripting' started by Kingpikachuyt, Nov 7, 2022.

  1. Kingpikachuyt

    Kingpikachuyt

    Joined:
    Nov 7, 2021
    Posts:
    13
    So i am making 2d platformer and adding audio to the game when i add the code to play the audio and try to play the audio in the game i get NullReferenceExceptions on the line where the soundManager plays the sound here's the code for player attacking where it plays a fireball sound.
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class PlayerAttack : MonoBehaviour
    4. {
    5.     [SerializeField] private float attackCooldown;
    6.     [SerializeField] private Transform firePoint;
    7.     [SerializeField] private GameObject[] fireballs;
    8.     [SerializeField] private AudioClip fireballSound;
    9.  
    10.     private Animator anim;
    11.     private PlayerMovement playerMovement;
    12.     private float cooldownTimer = Mathf.Infinity;
    13.  
    14.     private void Awake()
    15.     {
    16.         anim = GetComponent<Animator>();
    17.         playerMovement = GetComponent<PlayerMovement>();
    18.     }
    19.  
    20.     private void Update()
    21.     {
    22.         if (Input.GetMouseButton(0) && cooldownTimer > attackCooldown && playerMovement.canAttack())
    23.             Attack();
    24.  
    25.         cooldownTimer += Time.deltaTime;
    26.     }
    27.  
    28.     private void Attack()
    29.     {
    30.         SoundManager.instance.PlaySound(fireballSound);
    31.         anim.SetTrigger("attack");
    32.         cooldownTimer = 0;
    33.  
    34.         fireballs[FindFireball()].transform.position = firePoint.position;
    35.         fireballs[FindFireball()].GetComponent<Projectile>().SetDirection(Mathf.Sign(transform.localScale.x));
    36.     }
    37.     private int FindFireball()
    38.     {
    39.         for (int i = 0; i < fireballs.Length; i++)
    40.         {
    41.             if (!fireballs[i].activeInHierarchy)
    42.                 return i;
    43.         }
    44.         return 0;
    45.     }
    46. }
    and here is the sound manager code
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class SoundManager : MonoBehaviour
    4. {
    5.     public static SoundManager instance { get; private set; }
    6.     private AudioSource source;
    7.  
    8.     private void Awake()
    9.     {
    10.  
    11.         source = GetComponent<AudioSource>();
    12.  
    13.         //Keep this object even when we go to new scene
    14.         if (instance == null)
    15.         {
    16.             instance = this;
    17.             DontDestroyOnLoad(gameObject);
    18.         }
    19.         //Destroy duplicate gameobjects
    20.         else if (instance != null && instance != this)
    21.             Destroy(gameObject);
    22.     }
    23.     public void PlaySound(AudioClip _sound)
    24.     {
    25.         source.PlayOneShot(_sound);
    26.     }
    27. [INDENT]}
    [/INDENT]
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    With a null ref error, the rules are always the same.

    1. Find out what is null
    2. Find out why it's null
    3. Fix it.

    That being said, if you're having trouble with these steps, posting the error so we can see exactly what line it points to can help us to help you.

    If your error occurs here, then source is probably null as I assume you aren't passing in a null AudioClip

    Code (CSharp):
    1. public void PlaySound(AudioClip _sound)
    2.     {
    3.         source.PlayOneShot(_sound);
    4.     }
     
  4. Kingpikachuyt

    Kingpikachuyt

    Joined:
    Nov 7, 2021
    Posts:
    13
    upload_2022-11-7_14-52-36.png
    for desription on the error here is a description of the error in terms of the player attack script upload_2022-11-7_14-53-9.png
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,474
    I think you missed the point above. It's not about you telling us the what/why. The exception tells you what is NULL (not initialised) or at least the line it occurs on. When you find the what/why, you can then fix it. One of your references on that line is NULL. Debug it to found out. Use Debug.Log strategically to ensure things like your singleton is initialised or place a breakpoint and step through it with VS etc. :)

    Unless you're indirectly saying you don't know what a reference type is in C#. This is fundamental aspect of C# though and there's plenty of info online about value type versus reference types.

    https://www.tutorialsteacher.com/csharp/csharp-value-type-and-reference-type
     
  6. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    Code (CSharp):
    1. SoundManager.instance.PlaySound(fireballSound);
    This is the line your error points to. So break it apart. @MelvMay mentioned understanding the difference between a value and reference type. Once broken apart, you'll know that SoundManager and PlaySound can't be null because they aren't variables. Which leaves two options.
     
  7. Kingpikachuyt

    Kingpikachuyt

    Joined:
    Nov 7, 2021
    Posts:
    13
    i found a report from Microsoft's website on the difference between the 2 which it says .There are two kinds of types in C#: reference types and value types. Variables of reference types store references to their data (objects), while variables of value types directly contain their data. With reference types, two variables can reference the same object; therefore, operations on one variable can affect the object referenced by the other variable. With value types, each variable has its own copy of the data, and it's not possible for operations on one variable to affect the other (except in the case of in, ref, and out parameter variables; see in, ref, and out parameter modifier). this would be the difference between the 2 types correct?
     
  8. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,175
    You're overcomplicating this for yourself. A null exception means that something is null when it's not supposed to be null. For the line the console is pointing you to there are two possible sources:
    SoundManager.instance
    and
    fireballSound
    .

    To find the problem you need to insert Debug.Log lines directly before the line that is causing the error. If either of these lines says "true" then it's null.
    Code (csharp):
    1. Debug.Log($"SoundManager.instance: {SoundManager.instance == null}");
    2. Debug.Log($"fireballSound: {fireballSound == null}");
    3. SoundManager.instance.PlaySound(fireballSound);
     
    Last edited: Nov 7, 2022
    Kurt-Dekker likes this.
  9. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    This is not part of the three steps. It won't be helpful to you. I'm not kidding.

    How to fix a NullReferenceException error

    https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

    Three steps to success:
    - Identify what is null <-- any other action taken before this step is WASTED TIME
    - Identify why it is null
    - Fix that