c# - 如何正确创建对 Unity 对象的引用?
问题描述
我是 C# 和 Unity 的新手,无法找到问题的明确答案。
我正在尝试TextMeshProUGUI
在面板中创建一个简单的文本日志缓冲区。缓冲区本身工作正常,直到我尝试从另一个类访问它 - 我相信因为我没有正确创建对面板的引用。
这是我的TextMeshProUGUI
对象收集器代码:
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class TextLogControl : MonoBehaviour
{
public TextMeshProUGUI textPrefab; // Unity prefab
public List<TextMeshProUGUI> textItems = new List<TextMeshProUGUI>();
[SerializeField]
public int maxItems = 100;
public void LogText(string newTextString, Color newColor)
{
Instantiate(textPrefab, transform);
textPrefab.text = newTextString;
if (textItems.Count >= maxItems)
{
textItems.RemoveAt(0); // I should probably be destroying something, but that's another question
}
textPrefab.gameObject.SetActive(true);
textItems.Add(textPrefab);
}
// The above function works correctly if I write a test function within this same class
}
这是尝试访问该LogText()
函数的类的代码:
using System;
using UnityEngine;
public class World : MonoBehaviour
{
Color defaultColor = Color.black;
public TextLogControl textLog;
public void Init()
{
// I need to create a reference here somewhere, but nothing I am trying is working
textLog.LogText("Welcome - you made it!", defaultColor);
}
}
我将TextLogControl
脚本放在GameObject
持有TMP
对象的 Unity 上,并且可以自行运行。
我以为我是GameObject
通过将它拖到 Unity 中的 World 对象上来创建对持有者的引用,如下所示,但是当我调用时我仍然得到一个 NRE World.Init()
,这意味着我做错了什么,但我不知道是什么.
我认为这会创建未创建的引用
编辑:我收到的错误是
NullReferenceException:对象引用未设置为对象的实例
尝试运行时World.Init()
- 具体来说,textLog
它是空的,即使我已经将它拖到 Unity 中的适当位置(我相信)。
解决方案
由于评论太长了,空引用意味着它正在尝试访问不存在的东西。您要么忘记在编辑器中拖动某些内容,要么领先一步,并且有一些未注释的内容仍应被注释。您的代码正在使用不存在的东西。我建议您将这段代码添加到您的文件中,以检查错误是来自类的 NullRefrence 还是来自 else 代码。
TextMeshProUGUIs = textPrefab.GetComponent<TextMeshProUGUI>();
if (TextMeshProUGUIs == null)
{
Debug.LogError("No TextMeshProUGUI component found.");
}
推荐阅读
- angular - 单击时,登录按钮在离子中不起作用。
- java - 为 Android Studio 设置 ZeroMQ
- python - 气流回填和新的 dag 运行
- ios - 如何导入 Parse FacebookUtils?
- node.js - xml2json安装错误找不到Python可执行文件你可以设置PYTHON env变量
- python - 在 python 中调用 git
- apache - 在 Amazon Linux 实例上使用 docker-compose 安装 Apache OpenWhisk 卡在“等待 Whisk 调用程序启动...”
- css - 将 WooCommerce 产品图像缩小到移动视图中?
- javascript - 如何使用 this.props 将值传递给 onclick 回调
- codenameone - 代号一 SpanLabel 文本不占全角