Coin sfx not working and collision has stopped

NullReferenceException: Object reference not set to an instance of an object
BeerPickup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Scripts/BeerPickup.cs:13)

I get this error now when touching a coin

Here is my script

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class BeerPickup : MonoBehaviour

{

[SerializeField] AudioClip beerPickupSFX;



void OnTriggerEnter2D(Collider2D other)

{

    if (other.tag == "Player")

    {

        AudioSource.PlayClipAtPoint(beerPickupSFX, Camera.main.transform.position);

        Destroy(gameObject);

    }

}

}

Based on what you have given, I can only assume that you did not assign an audio clip to beerPickupSFX

My audio clip is assigned right?

When I added the audio clip and added the code for it the error started. Destroy on pickup worked before that part was added. My overrides are updated. It’s definitely reading the collision since it gives the error every time I touch the pickup

OK, Looks like it’s the camera then. I see a prefab called ‘Cameras’. I don’t know how many cameras are in there, but if none of them are marked with the ‘MainCamera’ tag, then Camera.main will be null. Unity usually creates a scene with a camera with a ‘MainCamera’ tag, but it doesn’t assign that tag to any new cameras

Edit: You also don’t need the Audio Sources on the beer prefabs because you are not using them. The AudioSource.PlayClipAtPoint(...) is going to create a new audio source at the position you give it, and it will destroy it again once the clip has played

I changed the main camera to “follow camera” but I’m getting the same error. I also deleted the pickup script from my prefab and reset it. So confused why the destroy on collision worked before the audio part was added. I would have thought Destroy would still work and not audio if anything?

Yeah, it doesn’t matter what it’s called. It has to have the ‘MainCamera’ tag. Currently it is ‘Untagged’
image

There is an exception so code execution exits the function. Anything after the exception (on line 13) will not execute

Thank you!!!

No problem

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms