【问题标题】:how to pause DontDestroyOnLoad audio in UNITY?如何在 UNITY 中暂停 DontDestroyOnLoad 音频?
【发布时间】:2018-02-27 15:30:13
【问题描述】:

我有这段代码可以在所有场景中播放音频,它工作正常,暂停也工作。但是当我离开现场并返回时,音频将不再暂停。我应该怎么做才能暂停音频?

public AudioClip sound;

public AudioSource source 
{ 
    get 
    { 
        return GetComponent<AudioSource>(); 
    }
}

void Start ()
{
    gameObject.AddComponent<AudioSource>(); 

    source.clip = sound;

    if (source.playOnAwake == true)
        source.Play ();    

    Button butn = GameObject.Find ("soundButton").GetComponent<Button>();

    butn.onClick.AddListener(PlaySoud);     
}

public void PlaySoud ()
{
    if (source.isPlaying)
    {
        source.Pause();
    }
    else
    {
        source.Play ();         
    }
}

void Awake()
{
    GameObject[] obj = GameObject.FindGameObjectsWithTag ("soundobject");

    if(obj.Length > 1)
    {
        Destroy (this.gameObject);
    }

    DontDestroyOnLoad (this.gameObject);
}

【问题讨论】:

    标签: unity3d


    【解决方案1】:
    1. 你可能会发现OnLevelWasLoaded很方便。

    2. 你这样做:

      public AudioSource source 
      { 
          get 
          { 
              return GetComponent<AudioSource>();
          } 
      }
      

      但我认为私有变量会更好。

    3. gameObject.AddComponent<AudioSource>();`
      

      为什么不在编辑器中添加这个组件?

    4. 我提到 (1.) 因为 Start()Awake() 仅在您实例化/创建对象时被调用。也在场景负载上。

      因此您的dontDestroyOnLoad 对象将不会在仍然存在的对象上再次执行Start()Awake()。 (只是为了澄清这一点)

    5. 如果您加载另一个包含音频对象的场景,则会调用一次 Awake()。在新装上。好的,直到这里。

      醒来的人会删除“旧”的,因为两者都有标签soundobject仔细检查所有场景都是这种情况!) - 但之后您在(可能)被破坏的对象上调用DontDestroyOnLoad。见answers.unity post - 有一个sn-p,他们首先调用DontDestroyOnLoad。和你的很相似。

    6. 您可以尝试在销毁之前致电source.Pause() - 这可能会提示您遇到问题。

    7. 使用

      Debug.Log("I am " + this.gameobject.name + " and I will be destroyed,  my audio is " + (source.isPlaying() ? "playing." : "not playing."));
      

      在销毁调用之前。然后检查层次结构和控制台以查看保留的内容和删除的内容。

    如果这不能解决问题,请报告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多