-3

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.

TEEBQNE
  • 6,104
  • 3
  • 20
  • 37
tormarod
  • 23
  • 1
  • 3
  • And I have created the AudioSource, attached the audio clip to it in the editor and attached the source to the planet GameObject. – tormarod May 28 '21 at 19:57
  • The error is pretty straightforward. On line 47, which is `source.Play();` there is a null reference and the only reference there is `source`. It means that whatever object this script is on is not the same object as your `AudioSource`. It means that the line in `Start` - `source = GetComponent();` is failing. – TEEBQNE May 28 '21 at 19:59
  • Yeah, I posted an answer, I'm sorry, it's my first project. Thank you very much for your answer. – tormarod May 28 '21 at 20:02
  • There is a big thread on how to deal with [`null references`](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it). Any posts regarding null references should be able to be answered here. – TEEBQNE May 28 '21 at 20:05

1 Answers1

1

My bad. Instead of creating an AudioSource component on the planet, I created a new AudioSource GameObject and then put it as a child of the planet. It's fixed

Sorry.

tormarod
  • 23
  • 1
  • 3