Cannot play sound on collision
Hi!
I have been reading lots of topics about similar problems, but I am still unable to find a solution (I am new to Unity).
I am trying to play a sound when a price of a 2D game is hit and I have tried with audio.Play(); and audio.PlayOneShot(impact); but I do not know what I am doing wrong.
This is my code.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(AudioSource))]
public class PriceBehaviour : MonoBehaviour {
new AudioSource audio;
public AudioClip impact;
void Start()
{
audio = GetComponent<AudioSource>();
}
// Update is called once per frame
void OnCollisionEnter2D (Collision2D newCollision) {
if (newCollision.gameObject.tag == "myRobot")
{
audio.PlayOneShot(impact);
Destroy(gameObject);
}
}
}
Thank you so much!
Answer by Statement · Oct 28, 2015 at 08:36 PM
You are destroying the game object that the audio source sits on.
It'll start to play, then immediately stop because the game object is destroyed.
Oh, I feel so stupid about my question. I thought that when it started playing it would play the sound until the end, even though the object was destroyed.
Thank you so much!
Your answer
Follow this Question
Related Questions
I have a problem playing an AudioSource 2 Answers
Sound doesn't play on Trigger??? 2 Answers
I want the audio to play when the player nears the object, but fade away when they walk away. 0 Answers
Audio playing at hightspeed and simoultanesly various times! 1 Answer
All my spectrums from GetSpectrumData are the same 0 Answers