I am new to C# and Unity and am having trouble finding a clear answer to my problem.
I am trying to create a simple TextMeshProUGUI text log buffer in a panel. The buffer itself works fine until I try to access it from another class - I believe because I am not creating the reference to the panel correctly.
Here is my code for the TextMeshProUGUI object collector:
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
}
Here is the code for the class that is trying to access the LogText() function:
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);
}
}
I am putting the TextLogControl script on the Unity GameObject that is holding the TMP objects, and that works on its own.
I thought that I was creating a reference to the holder GameObject by dragging it onto my World object in Unity as below, but I am still getting an NRE when I call World.Init(), which means that I'm doing something wrong, but I cannot figure out what.
I thought this would create the reference that is not being created

Edit: The error I'm receiving is
NullReferenceException: Object reference not set to an instance of an object
When trying to run World.Init() - specifically, textLog is null, even though I have got it dragged onto the appropriate spot in Unity (I believe).
transform.positionnot transformtextLoghasn't yet been assigned by the engine when.Init()is called. Remember that, when you run the game, everything has to be created and initialized, and that happens in a specific sequence. Also, consider using the defaultStart()method for your initialization rather than rolling your own.