基本上,我在“菜单”场景中有这个Text(scoreText),因此我已经在GameControlMenu.cs中启动了它,但是,当我目前正在尝试从其他脚本GameControl.cs更改其文本时,在我的“主要”场景中
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
在其他场景加载时使用它,如下所示:
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;
// ...
}
}
public class GameControl : MonoBehaviour
{
public static GameControl instance;
public int score = 5;
void Start()
{
// Store the value
GameControlMenu.StuffToShowOnScoreText = "PREVIOUS SCORE: " + score;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句