using UnityEngine;
using System.Collections;
public class InvaderControl : MonoBehaviour {
GameObject invaders;
public AudioClip deathSND;
void Start () {
}
void Update () {
}
void OnCollisionEnter(Collision obj)
{
Destroy(gameObject);
invaders=GameObject.Find("ScriptManager");
invaders.SendMessage("RemoveInvader",gameObject);
audio.clip=deathSND;
audio.Play();
while(audio.isPlaying){}
}
}
If I don’t have the line:
while(audio.isPlaying){}
The audio plays for a nano-second and doesn’t play the entire 2 second clip, this is consistant across all my audio bytes in the game, if I have that while there, the clip finishes but the game is haulted until the audio finishes (obviously).
So, how do I use Unity to start an audio playing in a thread of its own and have that thread terminate without writing my own thread controller?
Typically if objects have just one sound, you assign that in the audio source component in the inspector, and then just call audio.Play();. You only need to script audio.clips if the object does more than one sound.
But the problem here is that you’re destroying the object, so the audio only sounds for one frame, and then the audio source is destroyed. That’s why you only hear a nano-second. So probably the easiest thing is to instantiate an audio source that sticks around. Commonly you’d have this be a particle effect (so the audio plays while the particles are doing their thing), but you can just instantiate an audio source by itself.
As far as the while loop (not that you’d want it if you want to destroy the object immediately, which I’m sure you do), you’d want to do:
while(audio.isPlaying){
yield;
}
When the program hits a yield, it stops there and comes back the next frame where it left off. Also yield is useful for stuff like:
print ("Step 1");
yield WaitForSeconds(5);
print ("Here we are 5 seconds later....");
Or:
print ("Starting function");
yield SomeFunctionOrOther(10);
print ("Function has returned!");
function SomeFunctionOrOther(waitTime : float) {
yield WaitForSeconds(waitTime); // wait around uselessly
// do some other stuff
// ....
}
–Eric
Thanks again Eric, I’ll give these suggestions a try. The problem is, even my missile launch has the same problem, nano second play and they live for the extent of the fire to the collision either against the top barrier or against the invaders. More tomorrow 