DontDestroyOnLoad(Unity3D開發之五)

來源:互聯網
上載者:User

標籤:unity3d   dontdestroyonload   

Unity中我們從A情境切換到B情境的時候,A情境所有對象都會銷毀,但有時候我不需要銷毀某些東西。

比如一個簡單的遊戲的背景音樂,我不需要多次重複建立,多個情境播放這一個就行了。這個時候就需要用到DontDestroyOnLoad。

using UnityEngine;using System.Collections;public class MusicManager : MonoBehaviour {    string volumeSetting;void Awake () {        volumeSetting = PlayerPrefs.GetString("Volume");        if (volumeSetting == "False")        {            AudioListener.volume = 0;        }DontDestroyOnLoad(gameObject);}}

我在情境載入的時候初始化情境音樂,之後的進入遊戲情境,就不需要重新載入了。

注意:Unity 4.5之前的版本,在來回切換情境的時候會導致多次載入DontDestroyOnLoad的對象,導致出現多個的bug。
如果你是Unity 4.5之前,請使用一個static變數記錄你的對象是否已經初始化,防止多次建立。

上面是一個辦法,當然你也可以使用單例的方式代替DontDestroyOnLoad。

宣雨松的部落格中提到過這種方式,下面一段是宣雨松寫的,僅此記錄一下。
原文:http://www.xuanyusong.com/archives/2938

首先程式會進入static Global方法中,這個方法永遠只會走一遍,所以我在這裡建立一個GameObjcet,然後把Global這條指令碼綁定上去,我在DontDestroyOnLoad這個對象。

using UnityEngine;using System.Collections; public class Global :MonoBehaviour{    public static Global instance;     static Global()    {        GameObject go = new GameObject("Globa");        DontDestroyOnLoad(go);        instance = go.AddComponent<Global>();    }     public void DoSomeThings()    {        Debug.Log("DoSomeThings");    }     void Start ()     {        Debug.Log("Start");    } }

這樣這條指令碼就類似一個靜態指令碼了,而且這個遊戲對象也永遠不會因為切換情境而被銷毀。而且用起來非常方便。在需要調用它的地方直接調用就行了。

Global.instance.DoSomeThings();



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.