如何访问另一个场景中存在的游戏对象 [英] How to access gameobject present in another scene

查看:104
本文介绍了如何访问另一个场景中存在的游戏对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在unity3d中创建一个简单的猜数字游戏.

I am creating a simple number guessing game in unity3d.

我要在单击按钮时打开一个新场景,并从当前场景中更改已加载场景中存在的文本元素的文本.

I want to open a new scene on button click and change the text of a text element present in the loaded scene from the current scene.

我已经能够通过单击按钮来打开新场景,但是我如何访问其他场景中的文本元素,以便可以从当前场景中更改其文本. 到目前为止,这是我所拥有的,但显然会抛出NullReferenceException,因为我无法访问当前场景中另一个场景中的文本元素.

I have been able to open new scene on button click but how can i access the text element in other scene so that i can change its text from the current scene. This is what i have so far but it obviously throws NullReferenceException because i can't access the text element in another scene from current scene.

SceneManager.LoadScene("End Scene");
gameResultText.text = "You Won!!";        //<-------this line throws the exception
gameResultText.color = Color.green;

推荐答案

我想到的更好的解决方案:

Better solution I came up with:

制作一个设置静态字符串变量的脚本.该脚本必须在您的游戏场景中,并将保存结果.

public class ResultTextScript : MonoBehaviour
{
    public static string ResultText;

    void EndGame(){
    if (won){ //if won game
            ResultText = "You won!"
       }
       else //if lost game
       {
            ResultText = "You lost, try again another time!"
       }
       //Change scene with SceneManager.LoadScene("");
    }

}

将此脚本放在最终场景的结果文本中.该脚本将检索结果并将其显示.

Using UnityEngine.UI;

public class EndGameDisplayResult{

   Text text; 
   OnEnable(){
   Text.text = ResultTextScript.ResultText
   }
}

这样,它将在加载新场景后立即设置文本.

先前/替代方法:

如果您已经打开了场景,一种选择是向您赢了!"添加脚本.包含静态变量并引用了自身的文本.

就这样.

public class ResultTextScript : MonoBehaviour
{
    public static ResultTextScript Instance;

    void Awake(){
        if (Instance == null)
            Instance = this;
    }
}

然后,您可以在其他脚本中的任何位置(包括场景之间)调用对该GameObject的引用.

喜欢ResultTextScript.Instance

请注意,尽管您无法在Awake方法中调用引用,因为这是变量的初始化位置,但是您可以在调用Awake方法之后使用它.

Note though that you cannot call the reference in the Awake method, as that is where the variable is initialized, you can use it after the Awake methods have been called though.

基本上

  1. 将ResultTextScript添加到结束场景"中的Text对象中
  2. 例如,使用您的SceneManager方法从游戏场景"中打开结束场景".
  3. 确保已加载结束场景",然后在脚本中说出您想要更改文本gameObject go = ResultTextScript.Instance.gameObject

这篇关于如何访问另一个场景中存在的游戏对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆