0
votes

I was trying to create a trigger zone so that when you pass into a sphere collider with Is Trigger checked, the music starts, and when you exit the music stops. There's only one problem. If I actually start inside of the sphere collider, and take a step forward, the audio that was already on by 'play on awake' stops for a second and the audio restarts. I'm guessing that once I move the OnTriggerEnter Function is called and so it restarts. What way could I could start with the player inside the sphere without the audio restarting once I move?

    #pragma strict

private var theCollider: String;

function OnTriggerEnter (other : Collider)
{
theCollider = other.tag;
if(theCollider == "Player")
{
audio.Play();
audio.loop = true;
}

}

function OnTriggerExit (other : Collider)
{
theCollider = other.tag;
if(theCollider == "Player")
{
audio.Stop();
audio.loop = false;
}
}
1

1 Answers

2
votes

Answer

Use AudioSource.isPlaying to determine is audio clip is already playing. And invoke Play only if it doesn't.

function OnTriggerEnter (other : Collider)
{
    theCollider = other.tag;
    if (theCollider == "Player" && !audio.isPlaying)
    {
        audio.Play();
        audio.loop = true;
    }
}

Side note

Remember one golden rule: if variable can be made local, make it local.

Breaking of this rule resulted in a bug in the code that you have shown in your previous question (see my comment to RaycastHit Randomly Gets 2 Hits).

Here I'm talking about private var theCollider: String;. You can make theCollider local variable and you should.