【Unity跳转场景后保持原场景位置】

Unity 跳转场景保存原场景位置

首先获取和保持物体位置

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;

public class walk : MonoBehaviour
{
    
    
    public GameObject[] gos; //获取每个目标点
    public float speed = 20;  //用于控制移动速度
    int i = 0;             //用于记录是第几个目标点
                           //float des;             //用于存储与目标点的距离     
                           // Use this for initialization
    public float x;
    public float y;
    public Vector2 repos;//初始位置
    void Start()
    {
    
    
        i = PlayerPrefs.GetInt("i");
        if( i > 0)
            transform.position = gos[i - 1].transform.position;
    }

    // Update is called once per frame
    void Update()
    {
    
    
        Moon();
    }

    private void Moon()
    {
    
    
        //移向目标
        transform.position = Vector2.MoveTowards(this.transform.position, gos[i].transform.position, Time.deltaTime * speed);
        //移动到目标点进入答题场景
        if (transform.position == gos[i].transform.position)
        {
    
    
            SceneManager.LoadScene("Option");
            i++;
            // 保存目标点下标
            PlayerPrefs.SetInt("i", i);

            print(i);
        }
    }
}

设置不销毁

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

public class keep : MonoBehaviour
{
    
    
    // Start is called before the first frame update
    void Start()
    {
    
    
        DontDestroyOnLoad(gameObject);
    }

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

猜你喜欢

转载自blog.csdn.net/crush_oo/article/details/129932967