DontDestroyOnLoad

本文由博主(YinaPan)原创,转载请注明出处:http://www.cnblogs.com/YinaPan/p/Unity_DontDestroyOnLoad.html 

public static void DontDestroyOnLoad(Object target);

Parameters

Description

Makes the object target not be destroyed automatically when loading a new scene.

When loading a new level all objects in the scene are destroyed, then the objects in the new level are loaded. In order to preserve an object during level loading call DontDestroyOnLoad on it. If the object is a component or game object then its entire transform hierarchy will not be destroyed either.

当加载一个新关卡时,所有场景中所有的物体被销毁,然后新关卡中的物体被加载进来。为了保持在加载新关卡时物体不被销毁,使用DontDestroyOnLoad保持,如果物体是一个组件或游戏物体,它的整个transform层次将不会被销毁,全部保留下来。

// Make this game object and all its transform children
// survive when loading a new scene.
//当加载新场景的时候,使游戏物体和它所有的transform子物体存活下来
function Awake () {
	DontDestroyOnLoad (transform.gameObject);
}
 
using UnityEngine;
using System.Collections;
 
复制代码
using UnityEngine;
using System.Collections;

public class DontDestroyOnLOAD : MonoBehaviour {
    private Transform m_root = null;

    void Start() {
        Debug.LogError("Start");
        try {
            int i = 2;
            int[] tempInt = new int[2];
            int j = tempInt[2];
        }
        catch (System.Exception ex) {
            Debug.LogException(ex);
        }
        Debug.LogError("Start End");
    }

    void Awake() {
        Debug.LogError("Awake");
        string rootName = string.Format("{0}s", "DontDestroyOnLOAD");
        GameObject gameObj = new GameObject(rootName);
        GameObject.DontDestroyOnLoad(gameObj);
        m_root = gameObj.transform;
        Debug.LogError("Awake End");
    }

    void OnDisable() {
        Debug.LogError("OnDisable");
        Debug.LogError("OnDisable End");
    }

    void OnEnable() {
        Debug.LogError("OnEnable");
        Debug.LogError("OnEnable End");
    }
}
复制代码
第一种情况,start会默认执行;
最开始:脚本的勾勾,勾上,那么就会执行Awake、onEnbale、Start
去掉勾勾,执行onDisable 再加上勾勾执行OnEnable
image
image
 
第二种情况,start是没有执行的,只有在OnEnable时,才会在执行Start,且只执行一次
image
image
 
 
posted @   YinaPan  阅读(1265)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示