从场景1到场景2获取标签文本Unity

时间:2019-06-01 10:05:04

标签: c# unity3d

我已经在Unity中创建了一个简单的2d纸牌游戏,当用户在玩游戏时,某些信息会被捕获,例如(得分,尝试,时间),当用户赢得或输掉游戏时,就会出现相应的场景(游戏) over或Win场景)被触发,在这2个场景中,id喜欢将信息从游戏的得分,重试次数,时间字段复制到gameOver或Win的适当标签中,但这似乎是我做错了。 >

我试图在StackOverflow,youtube,web中找到类似的问题,我检查了文档,并尝试了不同的方法。 这是我目前使用的代码,对我来说似乎完全正确,我没有收到任何错误,标签上什么也没有。

'''
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class win_results : MonoBehaviour
{

    //public options script;

    public Text score_final_text;
    public Text tries_final_text;
    public Text time_final_text;

    public void player_win_results(){
       // script = a.getComponent<options>();

        if(options.user_lvl_choice=="easy"){
            GameObject tries_final = GameObject.Find("tries_text_lvl1"); //finds the object named score_results 
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl1"); //finds the object named score_results 
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl1"); //finds the object named score_results 
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
        else if(options.user_lvl_choice=="hard"){

            GameObject tries_final = GameObject.Find("tries_text_lvl2"); //finds the object named score_results 
            tries_final_text.text = tries_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject time_final = GameObject.Find("TimeCounter_lvl2"); //finds the object named score_results 
            time_final_text.text = time_final.GetComponent<Text>().text + "a"; //gets the Text property of it.

            GameObject score_final = GameObject.Find("score_lvl2"); //finds the object named score_results 
            score_final_text.text = score_final.GetComponent<Text>().text + "a"; //gets the Text property of it.
        }
    }

如上面的代码所示,我使用GameObject.Find作为文档说明,我已经仔细检查了名称和拼写错误,脚本已正确附加,我在输出中没有错误,什么也没发生。

正如您在上面看到的,我在末尾添加了一个额外的“ a”字符用于调试目的,该“ a”字符也未出现在输出中,这意味着在我的示例中,gameObject查找无法正常工作。

我做错了什么?

谢谢。

1 个答案:

答案 0 :(得分:2)

加载没有第二个参数的场景

SceneManager.LoadScene("scene2");

旧场景将被销毁,该场景中的所有GameObject也将被销毁,除非您在其上调用了DontDestroyOnLoad。

因此,如果您尚未完成此工作,那么在新场景中得到的是空数据。您可以打印要检查的值。

通过场景传递数据的最简单方法是使用静态字段。创建一个类并添加一些静态字段:

class Global
{
     public static string user_lvl_choice;
     public static string tries_final;
     ....
}

然后您可以在任何场景中设置或获取这些值。

Global.user_lvl_choice = "easy"
print(Global.user_lvl_choice);

了解更多: