I have this script attached to an object in the scene and I have my problem somewhat figured out, but I’m not sure exactly what to do about it.
I have a collider attached to this object as well as this script:
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public SceneManager sm;
public AudioClip clip;
void OnTriggerEnter(Collider other)
{
audio.clip = clip;
audio.Play();
Destroy(this.gameObject);
}
}
I’ve figured out that if I remove the Destroy call that it does play the audio, however I need to remove this gameObject from the scene and play the audio, but with this code it doesn’t seem like I can achieve this. Does anyone have any ideas?
You’re destroying the object and its AudioSource, thus the sound can’t be played anymore. You could use [PlayClipAtPoint][1] - this function creates a temporary AudioSource and plays the sound at the position specified, thus the object can rest in peace without stopping the sound:
void OnTriggerEnter(Collider other)
{
AudioSource.PlayClipAtPoint(clip, transform.position);
Destroy(this.gameObject);
}
[1]: http://unity3d.com/support/documentation/ScriptReference/AudioSource.PlayClipAtPoint.html
What I would do is add a coroutine(because I love them so much). Kinda like this:
void OnTriggerEnter(Collider other) {
StartCoroutine("PlayAudioAndDie");
}
public IEnumerator PlayAudioAndDie() {
audio.Play(); //assuming it is selected on the audio
renderer.enabled = false;
yield return new WaitForSeconds(audioclip.length); //not sure if this is called right but you get the point
Destroy(this.gameObject);
}
This should work. If it doesn’t I will try to assist you further. Hope I helped out.