如何使用 DontDestroyOnLoad?

how to use DontDestroyOnLoad?

所以这可能很简单,但我以前从未使用过 DontDestroyOnLoad(),也不知道该怎么做。我在切换到另一个屏幕时想保留的脚本中有一些值,我看到 DontDestroyOnLoad() 可以帮助我解决这个问题,但它似乎不适用于我的代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class data_transfer : MonoBehaviour
{
    DontDestroyOnLoad(transform.gameObject);
}

我收到此错误消息:Assets\scripts\data_transfer.cs(7,43): error CS1001: Identifier expected 就像我说的,这可能相对容易,但我是 unity 和 C# 的新手,所以如果你愿意提供帮助,谢谢。

DontDestroyOnLoad是一种方法。您只需在其他方法中调用它,例如 AwakeStart 例如像这样

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

Awake 在实例化 GameObject 时由 Unity 自动调用,因此这将防止您的对象在加载新场景时被销毁。

根据 Unity 的 documentation:

Do not destroy the target Object when loading a new Scene. The load of a new Scene destroys all current Scene objects. Call DontDestroyOnLoad to preserve an Object during level loading.

您需要将 DontDestroyOnLoad 调用包装在函数或 MonoBehaviour's built-in messages callbacks like Awake or Start 之一中。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MyClass: MonoBehaviour
{
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }
}