在场景中传递和维护变量值



到目前为止,我已经尝试过了。我想在整个场景中传递一个变量的值。我怎样才能保持价值。我想从一个场景到另一个场景获得一个游戏对象的位置,但脚本重新初始化了GameObject v变量的值。

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");
  }        
}   
}

虽然不清楚你到底尝试了什么,但我可以看出你尝试使用了DontDestroyOnLoad。这将是保持脚本在多个场景中持续存在的正确方法。用法上只有一个小错误。这就是start()的应用。

Start在脚本被启用的那一帧上被调用,就在任何Update方法第一次被调用之前。

不要在开头使用它,而要在awake()中使用它。

Awake在加载脚本实例时被调用。

只是为了确保,在调用DontDestroyOnLoad之前,您还可以设置transform.parent = null以防止从其他来源删除。当然,只有当它是对象的子对象时才会出现这种情况。

不要忘记重新工作这个逻辑。无论何时加载新场景,都会再次触发启动。这意味着在场景加载时,如果你保存了之前的对象,你会再次销毁它。

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

最新更新