关于DontDestroyOnLoad的坑呢 , 在度娘上一搜一大片,但是总感觉不那么直观 , 大多把DontDestroyOnLoad讲得太过概念化 , 不容易理解 。今天测试了一把 ,可以通过程序 ,将DontDestroyOnLoad理解得很详细。Unity3D DontDestroyOnLoad详解_Dont

废话不多说 , 开始介绍测试环境:

Unity3D DontDestroyOnLoad详解_3D_02

在①号场景中:

Unity3D DontDestroyOnLoad详解_Unity_03

Unity3D DontDestroyOnLoad详解_3D_04

代码:

using UnityEngine;
using System.Collections;

public class DontSaveTest : MonoBehaviour {

    public GameObject go;
	// Use this for initialization
	void Start () {
        DontDestroyOnLoad(go);
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    public void OnNextSceneButtonClick()
    {
        Application.LoadLevel("02_Second");
    }
}

注意 : go 绑定 Go(GameObject圆柱体)

在②号场景中:

Unity3D DontDestroyOnLoad详解_Dont_05

Unity3D DontDestroyOnLoad详解_Dont_06

代码:略。

运行游戏 , 当我们进入②号场景,②号场景会多一个Go(①号场景的圆柱体),如下图:


Unity3D DontDestroyOnLoad详解_3D_07

当然,有的时候,这是我们想要的。别急 ,点Back回到①号场景后 , Go又多了一个(为了更清楚,我把其中一个Go的位置移动了一下)

Unity3D DontDestroyOnLoad详解_Dont_08

好了,只要每次从②号场景进入到①号场景,那么Go都会复制一个。my god。


处理方案有很多 ,在这本人给出自己的处理方案:(修该①号场景代码)

using UnityEngine;
using System.Collections;

public class DontSaveTest : MonoBehaviour {

    public GameObject go;
    private static bool isNoDestroyHandler = true;//是否没有DontDestroyOnLoad处理
	// Use this for initialization
	void Start () {
        if (isNoDestroyHandler)
        {
            isNoDestroyHandler = false;
            DontDestroyOnLoad(go);
        }
	}
	
	// Update is called once per frame
	void Update () {
	
	}

    public void OnNextSceneButtonClick()
    {
        Application.LoadLevel("02_Second");
    }
}


问题的延伸:如何在②号场景中得到Go

方案①:

为Go加一个Tag , 我这里用的是Player

获取 : 

GameObject.FindGameObjectWithTag("Player");