首页 > 解决方案 > 如何正确创建对 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 中的适当位置(我相信)。

标签: c#unity3d

解决方案


由于评论太长了,空引用意味着它正在尝试访问不存在的东西。您要么忘记在编辑器中拖动某些内容,要么领先一步,并且有一些未注释的内容仍应被注释。您的代码正在使用不存在的东西。我建议您将这段代码添加到您的文件中,以检查错误是来自类的 NullRefrence 还是来自 else 代码。

    TextMeshProUGUIs = textPrefab.GetComponent<TextMeshProUGUI>();
    if (TextMeshProUGUIs == null)
    {
        Debug.LogError("No TextMeshProUGUI component found.");  
    }

推荐阅读