2016-08-02 65 views
0

我有用戶界面按鈕來切換聲音。 OnClick事件鏈接到這個單例遊戲對象。當我移動到下一個場景並返回到主場景時,我發現OnClick對象在對象仍然存在於層次結構中時丟失了!所以有什麼問題 ?用戶界面按鈕停止工作後,我加載另一場景

using UnityEngine; 
using System.Collections; 
using UnityEngine.UI; 

public class SoundsManagerController : MonoBehaviour { 

    static SoundsManagerController Instance = null;  



    void Awake() 
    { 
     // First we check if there are any other instances conflicting 
     if (Instance != null) 
     { 
            // If that is the case, we destroy other instances 
            Destroy(gameObject); 
     } 
     else { 
      // Here we save our singleton instance 
      Instance = this; 

      // Furthermore we make sure that we don't destroy between scenes (this is optional) 
      DontDestroyOnLoad(gameObject); 
     } 
    } 

    public void toggleSound(){ 

     Instance.GetComponent<AudioSource>().enabled = !Instance.GetComponent< AudioSource>().enabled; 
    } 

} 

回答

0

對按鈕使用單獨的畫布,並將它們保留爲單例對象的子項。

如果在場景中已經有畫布,請確保將按鈕設置爲畫布的子項,只要您要進入場景。

當這些應該解決你的問題時,你應該考慮不使用一個按鈕與單身人士的對象。在任何場景中獲取Start()中的單身人士對象,並從維護您的用戶界面佈局的已放置按鈕訪問聲音切換。

獲取啓動時保持切換方法調用函數的單例對象。

SoundManagerController soundManager; 

void Start() 
{ 
soundManager = GameObject.FindWithTag("audio_manager_tag").GetComponent <SoundManagerController>(); 
} 

從切換按鈕調用下面的方法。

public void CallToggleMethod() 
{ 
soundManager.toggleSound(); 
} 
+0

感謝您的幫助..但是你可以提供更好的方法鏈接或例子,因爲我不喜歡有多個畫布,讓他們的孩子的單身對象 – dotfreelancer

+0

凡在UI按鈕放置切換? –

+0

在畫布下 – dotfreelancer