统一播放c#

时间:2018-11-27 02:26:04

标签: c# unity3d

代码:

using UnityEngine;
using System.Collections;

public class DayNightController : MonoBehaviour {
public AudioSource daySong;
public AudioSource nightSong;
public Light sun;
public float secondsInFullDay = 120f;
[Range(0,1)]
public float currentTimeOfDay = 0;
[HideInInspector]
public float timeMultiplier = 1f;

float sunInitialIntensity;

void Start() {
    sunInitialIntensity = sun.intensity;

}

void Update() {
    UpdateSun();

    currentTimeOfDay += (Time.deltaTime / secondsInFullDay) * timeMultiplier;

    if (currentTimeOfDay >= 1) {
        currentTimeOfDay = 0;
    }
    if(currentTimeOfDay > 0.5){
        daySong.Stop();
        nightSong.Play(0);
    }
    if(currentTimeOfDay < 0.5){
        daySong.Play(0);
        nightSong.Stop();
    }
}

void UpdateSun() {
    sun.transform.localRotation = Quaternion.Euler((currentTimeOfDay * 360f) - 90, 170, 0);

    float intensityMultiplier = 1;
    if (currentTimeOfDay <= 0.23f || currentTimeOfDay >= 0.75f) {
        intensityMultiplier = 0;
    }
    else if (currentTimeOfDay <= 0.25f) {
        intensityMultiplier = Mathf.Clamp01((currentTimeOfDay - 0.23f) * (1 / 0.02f));
    }
    else if (currentTimeOfDay >= 0.73f) {
        intensityMultiplier = Mathf.Clamp01(1 - ((currentTimeOfDay - 0.73f) * (1 / 0.02f)));
    }

    sun.intensity = sunInitialIntensity * intensityMultiplier;
}
}

因此,当时间到了if命令的那一点时,我听到了这首歌,但是播放后1秒钟停了下来,音频剪辑超过了2分钟,我不知道为什么这样做,它会激活if命令,但随后停止,很抱歉成为菜鸟,但我需要帮助,因为我制作的游戏对我来说意味着世界,更多信息: 我在想什么,它会先激活if命令,然后再尝试下一个并停止音频剪辑,如果将[当前时间]的数字四舍五入会有所帮助吗?

1 个答案:

答案 0 :(得分:0)

您将在每一帧呼叫Play。您只需要在昼夜之间切换的画面上调用播放

void Update() {
    UpdateSun();

    bool isDay = currentTimeOfDay <= 0.5;
    currentTimeOfDay += (Time.deltaTime / secondsInFullDay) * timeMultiplier;
    if (currentTimeOfDay >= 1) {
        currentTimeOfDay = 0;
    }
    bool willBeDay = currentTimeOfDay <= 0.5;

    if(isDay && !willBeDay){
        daySong.Stop();
        nightSong.Play(0);
    }
    else if(!isDay && willBeDay){
        nightSong.Stop();
        daySong.Play(0);
    }
}