Error:
Can not play a disabled audio source UnityEngine.AudioSource:Play () CoinController:OnTriggerEnter2D (UnityEngine.Collider2D) (at Assets/Scripts/CoinController.cs:11)
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CoinController : MonoBehaviour
{
public AudioSource coinAudioSource;
private void OnTriggerEnter2D(Collider2D collider2D)
{
coinAudioSource.Play();
Destroy(gameObject);
}
}
CodePudding user response:
is the "coinAudioSource" attached to the same object as the CoinController script? Because Destroy(gameObject);
may destroy the audio Source as well then!
You can delete that delayed (for example 2s) if you wish: Destroy(gameObject, 2f);
If the coin should disappear immediately, you can disable the MeshRenderer in OnCollisionEnter.
CodePudding user response:
There can be two cases;
- If you attached the coinAudioSource to the gameobject which has CoinController script,
Destroy(gameObject);
This code destroy the coinAudioSource as well so, you can't play the audio source.
Like KYL3R explained above, you can insert delayed part;
- If you attached the coinAudioSource to other gameObject, you have to check the audio clip file to the audioSource correctly.
And you also have to check the mute or other disturbing setting of playing audioSource.
Except
you have to check object destroying, that is to say, whether collision occurs or not.