[英]saving player position while moving between scenes Unity 3D
我已經開始學習 3D 游戲開發,現在我已經達到了不斷變化的場景。 我查看了互聯網,但找不到可以在我的項目中實施的解決方案。
此時,我有兩個場景,作為主要場景的街道和酒吧場景。 我創建了一個滑動門,它有一個稱為門戶的對撞機,可以觸發場景切換。
我已經設法交換了場景,但是當我嘗試將 go 回到我的主要場景時,我重生了起點,而不是在酒吧出口處。 我試圖將播放器 position 保存在臨時變量中,但效果不佳。 我應該怎么做才能讓我的播放器從商店出口開始?
public class PlayerMotion : MonoBehaviour
{
//...
public static Vector3 playerPosition; // for respawning use
public static bool respawnNeeded = false;
CharacterController cController;
void Update()
{
if(respawnNeeded)
{
cController.transform.position = new Vector3(StreetToBarFFPortal.tempPosition.x,
StreetToBarFFPortal.tempPosition.y,
StreetToBarFFPortal.tempPosition.z);
respawnNeeded = false;
}
//..... some movement code
playerPosition = new Vector3(cController.transform.position.x, cController.transform.position.y, cController.transform.position.z);
}
public class StreetToBarFFPortal : MonoBehaviour
{
public static Vector3 tempPosition;
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Player"))
{
int index = SceneManager.GetActiveScene().buildIndex;
if(index==0)
{
PlayerMotion.respawnNeeded = true;
tempPosition = new Vector3(PlayerMotion.playerPosition.x,
PlayerMotion.playerPosition.y,
PlayerMotion.playerPosition.z-4);
}
index = 1 - index;// 1 transfers to 0 and 0 transfers to 1
SceneManager.LoadScene(index);
}
}
}
如果有幫助,我還有一個帶有單音設計模式的 GlobalManeger 腳本。
你有tempPosition
,我可以看到它在傳送之前用於存儲播放器 position,對嗎?
所以我看不到這個tempPosition
變量是從哪里來的。 是 static 還是來自單音腳本? 無論如何,您需要通過場景擁有此變量。 所以它應該在具有 DontDestroyOnLoad() 方法的腳本中;
你有兩個選擇:
將其存儲在 DontDestroyOnLoad()
在加載另一個場景之前將其存儲在 playerprefs 中,並在再次加載場景時將其加載回來。 由於您要存儲 Vector3,因此像這樣存儲 x、y 和 z:
PlayerPrefs.SetFloat("X", playerPosition.x); PlayerPrefs.SetFloat("Y", playerPosition.y); PlayerPrefs.SetFloat("Z", playerPosition.z);
和負載是這樣的:
float xpos = PlayerPrefs.GetFloat("X");
float ypos = PlayerPrefs.GetFloat("Y");
float zpos = PlayerPrefs.GetFloat("Z");
playerPosition = new Vector3(xpos, ypos, zpos);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.