温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Unity3D DontDestroyOnLoad详解

发布时间:2020-07-18 19:11:24 来源:网络 阅读:1016 作者:Aonaufly 栏目:游戏开发

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

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

Unity3D DontDestroyOnLoad详解

在①号场景中:

Unity3D DontDestroyOnLoad详解

Unity3D DontDestroyOnLoad详解

代码:

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详解

Unity3D DontDestroyOnLoad详解

代码:略。

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


Unity3D DontDestroyOnLoad详解

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

Unity3D DontDestroyOnLoad详解

好了,只要每次从②号场景进入到①号场景,那么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");


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI