如何更改脚本 Unity 中的游戏对象属性?

How do I change GameObject properties in scripts Unity?

我正在尝试 save/load 我的游戏。在加载方法中,每次我更改 GameObject 的属性时,都会应用这些更改,然后很快恢复。这是我的代码:

public void Load()
{
    SceneManager.LoadScene(sceneID);
    List<GameObject> rootObjects = new List<GameObject>();
    Scene scene = SceneManager.GetActiveScene();
    scene.GetRootGameObjects(rootObjects);

    int ncube = 0, npick = 0;
    for (int i = 0; i < rootObjects.Count; ++i)
    {
        GameObject obj = rootObjects[i];
        if (obj.CompareTag("Player"))
        {                                
            obj.transform.position = player.position;
            obj.transform.rotation = player.rotation;
            obj.transform.localScale = player.localScale;
        }
        else if (obj.CompareTag("Cube"))
        {
            obj.transform.position = cube[ncube].position;
            obj.transform.rotation = cube[ncube].rotation;
            obj.transform.localScale = cube[ncube].localScale;
            ++ncube;
        }
        else if (obj.CompareTag("Pickup"))
            obj.SetActive(pickup[npick++]);
        else if (obj.CompareTag("Door"))
            obj.SetActive(door);
        else if (obj.CompareTag("GreenWall"))
            obj.SetActive(greenWall);
    }
}

这些更改已应用于游戏对象,但会立即中止。我该如何解决?

包含这些代码行的脚本不是 GameObject 的组件。

编辑 1: 已更新完整代码。

问题可能是 SceneManager.LoadScene 下一帧 中完成。请参阅文档:https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html

它说:

When using SceneManager.LoadScene, the loading does not happen immediately, it completes in the next frame. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.

您在同一帧内更改值,因此在加载场景完成时它们将被覆盖。 Cou 可以使用一个事件来防止这种行为:https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html

问题是我认为

Scene scene = SceneManager.GetActiveScene();
scene.GetRootGameObjects(rootObjects);

在场景完全加载之前从场景中获取对象,以便重置它们。

来自Docu

When using SceneManager.LoadScene, the loading does not happen immediately, it completes in the next frame. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.


我猜你宁愿使用 SceneManager.sceneLoaded 并像

那样做你的事情
public void Load()
{
    SceneManager.LoadScene(sceneID);
}

也许在场景中的额外组件中:

void OnEnable()
{
    SceneManager.sceneLoaded += OnSceneLoaded;
}

void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
    // your stuff here
}

void OnDisable()
{
    SceneManager.sceneLoaded -= OnSceneLoaded;
}

虽然我们不 know/see 其中 playercube[ncube] 等来自...

为了在场景之间传输值,您应该开始使用 ScriptableObjects