Question by
SwastikBhattacharyya · Mar 27, 2020 at 12:14 PM ·
c#nullreferenceexceptiontextmeshnull reference exception
Using TextMeshProUGUI variable in a static function is returning a NullReferenceException
I have two scripts "GameManager.cs" and "RoomManager.cs"
GameManager.cs
using System.Collections;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
public class RoomManager : MonoBehaviour
{
private static Room _currentRoom;
private static Base _base;
private static Image _roomImage;
private static TextMeshProUGUI _roomName;
private static TextMeshProUGUI _roomDescription;
private static RoomManager _instance;
public void Start()
{
_roomName = GameObject.Find("RoomName").GetComponent<TextMeshProUGUI>();
Debug.Log(_roomName.text);
_roomDescription = GameObject.Find("RoomDescription").GetComponent<TextMeshProUGUI>();
_roomImage = GameObject.Find("RoomImage").GetComponent<Image>();
_instance = this;
}
public static void EnterBase()
{
_currentRoom = (Base) AssetDatabase.LoadAssetAtPath("Assets/Entities/Room/Objects/Base.asset", typeof(Base));
Debug.Log($"<size=25>The <b>player</b> is currently at <color=green>{_currentRoom.roomName}</color></size>");
_roomImage = GameObject.Find("RoomImage").GetComponent<Image>();
_roomImage.sprite = _currentRoom.roomImage;
_roomName.text = string.Empty;
_roomDescription.text = string.Empty;
_instance.StartCoroutine(ChangeRoomName(_roomName, _currentRoom.roomName));
}
private static IEnumerator ChangeRoomName(TMP_Text text, string changedText, float speed = 0.125f)
{
foreach (var character in changedText)
{
text.text += character;
yield return new WaitForSeconds (speed);
}
yield return _instance.StartCoroutine(ChangeRoomDescription(_roomDescription, _currentRoom.roomDescription, 0.050f));
}
private static IEnumerator ChangeRoomDescription(TMP_Text text, string changedText, float speed = 0.125f)
{
text.text = string.Empty;
foreach (var character in changedText)
{
text.text += character;
yield return new WaitForSeconds (speed);
}
}
}
I call the EnterBase method at the Start function of the RoomManager script but it is throwing a NullReference Exception at _roomName.text = string.Empty;
However, the _roomImage.sprite = _currentRoom.roomImage; is working fine. In the Start Method, the Debug.Log is returning the correct text (expected value) so why is the _roomName variable throwing a NullReferenceException in the EnterBase function?
Comment