So I want to play an audio source when a collision trigger happens, but unity throws this exception:
ArgumentNullException: Value cannot be null. Parameter name: source UnityEngine.AudioSource.Play () (at <8e2857b79be4468ca1c28dda75978191>:0) PlanetMovement.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/PlanetMovement.cs:47)
This is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlanetMovement : MonoBehaviour
{
    bool moveAllowed;
    Collider2D col;
    public float moveSpeed;
    public GameObject restartPanel;
    private AudioSource source;
    // Start is called before the first frame update
    void Start()
    {
        source = GetComponent<AudioSource>();
        col = GetComponent<Collider2D>();
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            transform.position = Vector2.MoveTowards(transform.position, touchPosition, moveSpeed * Time.deltaTime);
        }
    }
    public void GameOver()
    {
        Invoke("Delay", 1.5f);
    }
    public void Delay()
    {
        restartPanel.SetActive(true);
        Time.timeScale = 0;
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Asteroid")
        {
            source.Play();
            GameOver();
            Debug.Log("Hit");
        }
    }
}
The collision trigger works perfectly without the audio source. I don't know what's going on. The asteroids are a prefab spawned dynamically, if that's useful info.
Thank you.
 
    