API: Object.DontDestroyOnLoad

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.

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour 
{
    void Awake() 
    {
        DontDestroyOnLoad(transform.gameObject);
    }
}

使用场景举例:

在场景1中某一个脚本的Start方法中,DontDestroyOnLoad(A)

接着切换到场景2中,理所当然A对象被保留了下来

如果在从2场景再次回到1场景,那么又执行了一遍DontDestroyOnLoad(A)然而之前你的A对象却没有被施放,这样就会无线循环下去了。

解决方法如:

1.可以建立缓存场景,将需要保留的所有对象放在一个空的对象下,这样保证了保留一直循环和保留重复的问题,

2.可以使用相同对象判断方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值