2015-10-26 48 views
1

到目前爲止,我已經嘗試過。我想要在場景中傳遞變量的值。我如何保持價值。我想從一個場景獲取遊戲對象的位置,但腳本重新初始化了GameObject的值。在場景中傳遞並保持變量值

using UnityEngine; 
using System.Collections; 

public class Maintainer : MonoBehaviour { 

public GameObject v;//I want to maintain this value across the scene 
public GameObject cameraGO; 
static Maintainer instance; 

// Use this for initialization 
void Awake() { 

} 

void Start() { 

    Debug.Log("awake "); 

    if (instance != null) 
    { 
     Debug.Log("Instance not null"); 
     //Dont want new 
     Destroy(gameObject); 
    } 
    else 
    { 
     Debug.Log("instance is null"); 
     DontDestroyOnLoad(gameObject); 
     instance = this; 
    } 
    //DontDestroyOnLoad(gameObject.transform); 
} 

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

    if (cameraGO != null) 
    { 
     v = cameraGO; 
     Debug.Log("camera position " + cameraGO); 
    } 
    else { 
     Debug.LogError("Camera not found!"); 
    } 

    Debug.Log("Camera Position : "+ v); 

} 

void OnGUI() { 
    if (GUI.Button(new Rect(10, 10, 150, 100), "Load Scene 2")){ 
     print("You clicked the button!"); 
     Application.LoadLevel ("Scene2PassValue"); 
    } 
    if (GUI.Button(new Rect(10, 150, 150, 100), "Load Scene 1")) 
    { 
    // Debug.Log("Camera Position : " + v.transform.position); 
     print("You clicked the button!"); 
     Application.LoadLevel("Scene1PassValue"); 
    }   
} 
} 
+0

您是否嘗試將該值設爲靜態類字段? –

+0

你能更具體嗎?你想要傳遞哪種價值,是你需要在另一個課程中引用的價值? – Takarii

+0

@Takarii gameobject v值 –

回答

0

所有的辛苦也沒有明確你嘗試過什麼,我可以看到你試圖用DontDestroyOnLoad。這將是保持腳本在多個場景中持續存在的正確方法。使用中只有一個小小的錯誤。這就是start()中的應用。

在第一次調用任何Update方法之前啓用腳本時,將在框架上調用啓動。

不是在開始時使用它,而是想用它代替awake()

在加載腳本實例時調用喚醒。

只是爲了確保,你打電話之前DontDestroyOnLoad你也可以設置transform.parent = null防止刪除從其他來源。只有當它是一個物體的孩子時,這種情況纔是正確的。

不要忘了重新工作這個邏輯。每當你加載一個新的場景,啓動將再次觸發iirc。這意味着在場景加載時,如果你保存了以前的對象,那麼你會再次摧毀它。

// If we do not have a instance yet 
if (instance == null) 
{ 
    Debug.Log("Instance null"); 
    instance = this; 
} 
+0

我添加了我的條件來喚醒函數但問題仍然存在,而我希望在整個場景中保持gameobject v的位置 –