重新加载场景后保留对象

时间:2018-08-23 17:01:38

标签: unity3d animation reload scene

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

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

public static SpriteRenderer towerAnimation;


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

“ GameManager”脚本更新中的以下代码:

public static int counterQuestionChances = 2;

void DestroyTower()
    {
        if (counterQuestionChances == 1)
        {
            Tower.towerAnimation.SetTrigger("error 1");

        }
        else
        {
            if (counterQuestionChances == 0)
            {
                Tower.towerAnimation.SetTrigger("error 2");

            }
        }

但是它不起作用。我在黑暗中拍摄照片,因为我不知道该如何解决。如果您能给我提出任何可以帮助我解决问题的想法,我将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

您将不得不使用Unity拥有的SceneManagement库,以便在场景更改时调用下面称为OnActiveSceneChanged的方法。

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
    }
}