ArgumentNullException: Value cannot be null. (Trying to add audio to my 2d game but struck with this error)

CODE:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{



    // Start is called before the first frame update
    public AudioSource AS;
    private Rigidbody2D R;
    public static int t = 0;
    private Vector3 scale;
    private Vector3 size;
    private Vector3 coin;
    void Start()
    {
        scale = new Vector3(1.0f, 1.0f, 1.0f);
        size = new Vector3(0.5f, 0.5f, 0.5f);
        coin = new Vector3(Random.Range(0.0f, 1.0f), 0.0f, 0.0f);
        R = GetComponent<Rigidbody2D>();
        AS = gameObject.GetComponent<AudioSource>();

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKey(KeyCode.A))
        {
            R.AddForce(-transform.right * 0.5f, ForceMode2D.Impulse);


        }
        if (Input.GetKey(KeyCode.D))
        {
            R.AddForce(transform.right * 0.5f, ForceMode2D.Impulse);


        }

        if (Gold.hit == 2 && transform.localScale != size)
        {
            transform.localScale = transform.localScale - scale;
            Gold.hit = 0;
        }
        else
        {
            print("enter A or D");
        }

        if (t ==1)
        {
            AS.Play();
            t = 0;

        }
    }

    void OnCollisionEnter2D(Collision2D col)
    {
      if(col.gameObject.name=="A"|| col.gameObject.name == "B")
        { 
            transform.localScale = transform.localScale + scale;
          
         }
     }
}

Error I am getting:

Assign an audio clip to the audio source in the inspector

@N-8-D-e-v I have the same problem, and that didn’t seem to work. I have the audio source displayed in my player script, and in another scene, the formatting for “source.PlayOneShot()” seemed to work just fine. I don’t understand why with the same formatting, it returns a value of null, even if I manually drag in the audio file to the required field.

The reason why this happened is that you tried to access a method from AS but AS is null.
In your Start function you assign it through gameObject.GetComponent<AudioSource>();, this will only work if the GameObject this script is attached to has an audio source component. So you need to make sure there’s an audio source component on it.

If it helps, here’s an example: