Unity 在另一个 script/scene 中更改一个对象的文本

Unity Changing the Text of an object in another script/scene

基本上,我的 "Menu" 场景中有这个文本 (scoreText),因此我在 GameControlMenu.cs 中启动了它,但是,我正在尝试更改它的文本脚本 GameControl.cs 而我目前正在 "Main" 场景中。

GameControlMenu.cs:

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

public class GameControlMenu : MonoBehaviour
{

public static GameControlMenu instanceMenu;

public Text scoreText;

void Start()
{
    //does stuff but not important to question
}
}

GameControl.cs:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

public class GameControl : MonoBehaviour
{
public static GameControl instance;

public int score = 5;

void Start()
{   
    GameControlMenu.instanceMenu.scoreText.text = "PREVIOUS SCORE: " + score;
}
}

此设置适用于我从另一个文件访问的其他几个变量,但无论出于何种原因,这只会不断向我抛出错误:NullReferenceException:未将对象引用设置为实例一个对象

感谢任何帮助:)

您不能执行 GameControlMenu.instanceMenu...,因为 GameControlMenu 在您描述的另一个场景中,并且该实例不在当前场景中。

但是您可以先将值存储在某处,然后让 GameControlMenu 在其他场景加载时使用它,如下所示:

GameControlMenu.cs

public class GameControlMenu : MonoBehaviour
{

    public static GameControlMenu instanceMenu;

    public static string StuffToShowOnScoreText { get; set; }

    public Text scoreText;

    void Awake()
    {
        // So that it loads the text on start
        scoreText.text = StuffToShowOnScoreText;
        // ...
    }
}

GameControl.cs

public class GameControl : MonoBehaviour
{
    public static GameControl instance;

    public int score = 5;

    void Start()
    {   
        // Store the value 
        GameControlMenu.StuffToShowOnScoreText = "PREVIOUS SCORE: " + score;
    }
}