Unity關於銷燬和保留物體

最近在做VR項目的時候,當我從A場景跳到B場景,但是它使用的還是A場景的手柄和眼鏡,並沒有把A場景的手柄和眼鏡銷燬,而它使用的是unity內置的一個函數,一開始通過查資料,我發現只要不勾選Persist On Load,在進入下一個場景之後,便不會再保存上一個場景的手柄和眼鏡,而這種加載另外一個場景而保存前一個場景的物品,是通過Unity內置的一種銷燬方式來實現的,本節就來講一下unity裏面的幾種銷燬和保留的方式。
這裏寫圖片描述
方法一:Object.Destroy
public static void Destroy(Object obj, float t = 0.0F);
前面的參數是要被銷燬的物體或者是組件,後面是多少時間後被銷燬
使用起來非常簡單
方法二:Object.DontDestroyOnLoad
public static void DontDestroyOnLoad(Object target);
其實這種銷燬方式也很簡單,我們可以自己做一下試驗,新建一個場景A,再新建一個場景B,我們通過在A場景點擊按鈕,加載B場景:
這裏寫圖片描述
同時新建一個加載的腳本LoadB,在A場景創建一個Cube什麼的,作爲我們加載場景之後要保存的物體,把腳本掛上去,腳本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class LoadB : MonoBehaviour {

    private void Awake()
    {
        DontDestroyOnLoad(this.gameObject);
    }
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
    public void LoadBScene()
    {
        SceneManager.LoadScene("B");
    }
}

運行,可以發現我們的場景中多了一個DontDestroyOnLoad的場景
這裏寫圖片描述
就算我們加載到下一個場景,它也是存在的,所以說,這種銷燬方式特別適用於在我們切換場景後,但又還要用到上一個場景的物品的情況。
方法三:Object.DestroyImmediate
public static void DestroyImmediate(Object obj, bool allowDestroyingAssets = false);
官方解釋:
This function should only be used when writing editor code since the delayed destruction will never be invoked in edit mode. In game code you should use Object.Destroy instead. Destroy is always delayed (but executed within the same frame). Use this function with care since it can destroy assets permanently! Also note that you should never iterate through arrays and destroy the elements you are iterating over. This will cause serious problems (as a general programming practice, not just in Unity).
這個方法是運用於編輯器模式下操作,一旦刪除了物體,就永久都被刪除,而在遊戲運行時,還是建議使用Destroy()方法。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章