[英]Pass and maintain variable value across the scene
到目前为止,我已经尝试过了。 我想在整个场景中传递变量的值。 我如何保持价值。 我想从一个场景到另一个场景获取游戏对象的位置,但是脚本重新初始化了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()
的应用程序。
如果在首次调用任何Update方法之前启用了脚本,则会在框架上调用Start。
与其在开始时使用它, awake()
在awake()
使用它。
加载脚本实例时将调用Awake。
只是为了确保,在调用DontDestroyOnLoad
之前,您还可以设置transform.parent = null
以防止从其他来源删除。 仅当它是对象的子对象时,这种偏离路线才是这种情况。
并且不要忘了重做此逻辑。 每当您加载新场景时,iirc都会再次触发开始。 这意味着在场景加载中,如果保存了先前的对象,则将其再次销毁。
// If we do not have a instance yet
if (instance == null)
{
Debug.Log("Instance null");
instance = this;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.