Hi! I’m new here and also with Unity and programming in C#… So I have some trouble.
I want to take a font asset (TMP_FontAsset of TextMeshPro) from the inspector using my class Manager, and then change every text with the FontText script attached, so its font is the one I took from the inspector.
Here is what I use for this in Manager.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;
using System;
public class Manager : MonoBehaviour {
// ...
public static Manager Instance { set; get; }
[Header("Global Text")]
public TMP_FontAsset GlobalFont;
// ...
}
And this is the FontText script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class FontText : MonoBehaviour {
private TextMeshProUGUI m_TextMeshPro;
private TMP_FontAsset m_Font = Manager.Instance.GlobalFont;
void Start () {
UpdateFontText();
}
void UpdateFontText () {
if (m_TextMeshPro == null && GetComponent<TextMeshProUGUI>() != null) {
m_TextMeshPro = GetComponent<TextMeshProUGUI>();
m_TextMeshPro.font = m_Font;
}
}
}
So the thing is that with this code it works, it changes the font, but it gives me a NullReferenceException: Object reference not set to an instance of an Object
I hope someone could help me, I have no idea why this happens… I need the code to be correct even if it apparently works. I tried to assign the font (m_Font = Manager.Instance.GlobalFont; ) in the Start() function or in the Update(), but then the font doesn’t change and the error is still there… Any ideas?
Thank you very much!
Edited:
Here are the lines of the error:
NullReferenceException: Object reference not set to an instance of an object
FontText…ctor () (at Assets/Scripts/FontText.cs:9)