zoukankan      html  css  js  c++  java
  • DontDestroyOnLoad(Unity3D开发之五)

    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();



  • 相关阅读:
    【CCPC2020网络赛11】Convolution
    【CCPC2020网络赛02】Graph Theory Class
    全国中学生网安竞赛出题总结
    XDU2020ACM校赛总结
    CTF错误集合
    【洛谷2916】图的遍历
    20200420(ABC)题解 by 辛晓东
    20200402(ABC)题解 by 孙晨曦
    20200406(ABC)题解 by 徐光旭
    20200407(DE)题解 by 孙晨曦
  • 原文地址:https://www.cnblogs.com/blfshiye/p/4265656.html
Copyright © 2011-2022 走看看