C# Unity C中的空引用问题#
我正在尝试获取对Unity中两个游戏对象的引用,它们是“ScoreEntryContainer”及其子对象“template”: 在我的脚本中,我添加了两个公共转换变量以获得对这些变量的引用。但是,Unity抛出一个C# Unity C中的空引用问题#,c#,unity3d,C#,Unity3d,我正在尝试获取对Unity中两个游戏对象的引用,它们是“ScoreEntryContainer”及其子对象“template”: 在我的脚本中,我添加了两个公共转换变量以获得对这些变量的引用。但是,Unity抛出一个NullReferenceException,指向对“模板”的引用 模板是一个包含三个文本UI游戏对象的容器 在inspector中,我也将这些游戏对象指定给脚本组件。错误指向下面代码中的Debug.Log行: public class ScoreboardScript : Mo
NullReferenceException
,指向对“模板”的引用
模板是一个包含三个文本UI游戏对象的容器
在inspector中,我也将这些游戏对象指定给脚本组件。错误指向下面代码中的Debug.Log行:
public class ScoreboardScript : MonoBehaviour
{
public Transform container;
public Transform template;
private List<ScoreEntry> scoreEntryList;
private List<Transform> scoreEntryTransformList;
public void Awake()
{
template.gameObject.SetActive(false);
scoreEntryList = new List<ScoreEntry>()
{
new ScoreEntry(10,150f),
new ScoreEntry(20,150f),
new ScoreEntry(30,150f)
};
foreach(ScoreEntry sc in scoreEntryList)
{
float templateHeight = 25f;
Transform entry = Instantiate(template, container);
RectTransform entryRectTransform = entry.GetComponent<RectTransform>();
entryRectTransform.anchoredPosition = new Vector2(0, -templateHeight * scoreEntryList.IndexOf(sc));
entry.gameObject.SetActive(true);
int rank = 0;
//entry.Find("SerialNoText").GetComponent<Text>().text = rank.ToString();
Debug.Log(entry.Find("SerialNoText").GetComponent<Text>().text); // Error here
float time = sc.time;
int minutes = (int)(time / 60);
int seconds = (int)(time % 60);
//entry.Find("TimeText").GetComponent<Text>().text = minutes.ToString() + ":" + seconds.ToString();
}
}
公共类记分板脚本:单行为
{
公共转换容器;
公共转换模板;
私人名单记分表;
私有列表scoreEntryTransformList;
公共图书馆
{
template.gameObject.SetActive(false);
scoreEntryList=新列表()
{
新记分表(10150F),
新计分表(20150F),
新记分表(30150F)
};
foreach(scoreEntryList中的ScoreEntry sc)
{
浮动模板高度=25f;
转换条目=实例化(模板、容器);
RectTransform entryRectTransform=entry.GetComponent();
entryRectTransform.anchoredPosition=新向量2(0,-templateHeight*scoreEntryList.IndexOf(sc));
entry.gameObject.SetActive(true);
int秩=0;
//entry.Find(“SerialNoText”).GetComponent().text=rank.ToString();
Debug.Log(entry.Find(“SerialNoText”).GetComponent().text);//此处出错
浮动时间=sc时间;
整数分钟=(整数)(时间/60);
整数秒=(整数)(时间%60);
//entry.Find(“TimeText”).GetComponent().text=minutes.ToString()+“:“+seconds.ToString();
}
}
你知道为什么会这样吗
见检查员:
条目
是对模板
游戏对象的引用
请参见inspector中的模板
:
模板上没有文本组件。因此,调用条目.Find(“SerialNoText”).GetComponent()
返回空引用。好的,我已经解决了
问题是因为我在UI中使用了TextMeshPro,而不是引发空异常的文本。因此我在脚本中相应地对其进行了更改。有关何时使用该标记的信息,请参阅。此问题不是该标记的适当位置。输入应获得对模板的引用。有关屏幕截图,请参阅编辑。您能告诉我们吗ScoreboardScript.cs中第41行是哪一行(每个错误消息)?它仍然给了我相同的错误。不确定没有孩子是什么意思。我已将游戏对象命名为“SerialNoText”就像我对其他所有游戏对象的命名一样。我认为问题在于,当模板被实例化时,它的子对象没有被实例化。@Shand'Silva我使用注释和答案中的新信息更改了答案。@Ruzihm甚至没有通过一个更具体的错误来统一?Afaik类似于您试图获取组件XY,但GameObject没有这样的组件
@derHugo据我所知,检查GameObject是否有组件的有效方法是使用GetComponent
并检查结果是否为空。我认为它不会抛出错误。