Unity3d 重新加载场景后保留对象

Unity3d 重新加载场景后保留对象,unity3d,animation,reload,scene,Unity3d,Animation,Reload,Scene,在我的问答游戏的一个场景中,我有一个动画对象,当按下移动到下一个问题的按钮(按钮重新加载场景)时,该对象会更改为另一个动画。我想在场景重新加载后保留动画,即引用到对象的最后一个动画,但我不知道如何保存。对象始终返回其正常状态(第一个动画) 我目前有一个名为“tower”的脚本,它引用了我创建静态对象和DontDestroyOnLoad函数的对象: public static SpriteRenderer towerAnimation; void Awake() { DontDestr

在我的问答游戏的一个场景中,我有一个动画对象,当按下移动到下一个问题的按钮(按钮重新加载场景)时,该对象会更改为另一个动画。我想在场景重新加载后保留动画,即引用到对象的最后一个动画,但我不知道如何保存。对象始终返回其正常状态(第一个动画)

我目前有一个名为“tower”的脚本,它引用了我创建静态对象和DontDestroyOnLoad函数的对象:

public static SpriteRenderer towerAnimation;


void Awake()
{
    DontDestroyOnLoad(gameObject);
    towerAnimation = GetComponent<SpriteRenderer>();
}

但它不起作用。我在黑暗中拍摄,因为我不知道如何解决这个问题。如果你能给我一些能帮我解决这个问题的想法,我将不胜感激。谢谢

当场景更改时,您必须使用Unity提供的SceneManagement库。下面调用的方法onActivanceChanged将被调用

using UnityEngine.SceneManagement;

public class Tower : MonoBehaviour
{
    public static SpriteRenderer towerAnimation;
    public int storedCounter = 0;
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        towerAnimation = GetComponent<SpriteRenderer>();
        SceneManager.activeSceneChanged += OnActiveSceneChanged;
    }

    private void OnActiveSceneChanged(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.Scene currentScene)
    {
        //tower animation stuff here
    }
}
使用UnityEngine.SceneManagement;
公共级塔楼:MonoBehavior
{
公共静电喷灌塔;
公共整数存储计数器=0;
无效唤醒()
{
DontDestroyOnLoad(游戏对象);
towerAnimation=GetComponent();
SceneManager.activeSceneChanged+=OnActiveSceneChanged;
}
活动上的私有无效已更改(UnityEngine.SceneManagement.Scene场景,UnityEngine.SceneManagement.Scene当前场景)
{
//塔动画的东西在这里
}
}

嗯,我不确定所有的东西都是什么,但不要忘记,不仅所有的东西都会被破坏,还会重新运行。因此,您的“GameManager”脚本将运行Awake()、Start()等。因此,Awake()将被调用(即DontDestroyOnLoad)太多次。看看这个。。。。接下来,基于您的逻辑,您的动画触发器将永远不会发生。另外,我不想为towerAnimation的静态实例操心,因为您无论如何都不会使用它。谢谢,但我不知道如果我不使用DontDestroyOnLoad,我必须保留该对象的哪些替代方案。你有什么建议?变量“storedCounter”的确切含义是什么?因为我看不出这有什么用。在场景之间存储数据,或者至少在脚本的某个地方保留变量
using UnityEngine.SceneManagement;

public class Tower : MonoBehaviour
{
    public static SpriteRenderer towerAnimation;
    public int storedCounter = 0;
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        towerAnimation = GetComponent<SpriteRenderer>();
        SceneManager.activeSceneChanged += OnActiveSceneChanged;
    }

    private void OnActiveSceneChanged(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.Scene currentScene)
    {
        //tower animation stuff here
    }
}