当玩家处于Y 0.5位置时播放声音

时间:2014-11-12 18:55:07

标签: c# unity3d

我的代码:

void Update() 
{
    //Restart level
    if (gameObject.transform.position.y < -0.5) 
    {
        PlayerPrefs.SetInt("CubePointsLvl", 0);
        StartCoroutine( Wait3Seconds() );
        //rigidbody.AddForce(0,-100000,0);
        //transform.position = new Vector3(inputSpawnX, inputSpawnY, inputSpawnZ);
    }
}

//Wait 3 second
IEnumerator Wait3Seconds()
{
    audio.PlayOneShot(DeadSound, 1.0F);
    yield return new WaitForSeconds (0.3f);
    Application.LoadLevel(Application.loadedLevel);
}

当玩家处于Y 0.5位置然后重新开始游戏时,我想发出声音。但是当我调试代码时,声音就会循环播放,我知道原因,但我不知道如何解决它。我怎样才能做到这一点?并解释?我正在使用C#。

1 个答案:

答案 0 :(得分:2)

您在播放器低于-0.5的每一帧开始新的协程,而不是仅在玩家低于-0.5第一时间之后才开始。您可以使用标志来防止协程再次启动。

private bool alreadyDead = false;

public void Update() {
    // Only execute if we've gone below -0.5 for the first time
    if (gameObject.transform.position.y < -0.5 && 
        alreadyDead == false) 
    {
        // Set a flag indicating this has been executed
        alreadyDead = true;
        PlayerPrefs.SetInt("CubePointsLvl", 0);
        StartCoroutine( Wait3Seconds() );
    }
}

public IEnumerator Wait3Seconds()
{
    audio.PlayOneShot(DeadSound, 1.0F);
    yield return new WaitForSeconds (0.3f);
    Application.LoadLevel(Application.loadedLevel);
}