So I’ve been following this basic tutorial about Unity when I ran into issues with trying to run a create a score variable that displays in the UI.
using UnityEngine.UIElements;
using UnityEngine;
public class Score : MonoBehaviour
{
public Transform player;
public TextElement score;
void Update()
{
score.text = player.position.z.ToString("0");
}
}
This is the error I got:
NullReferenceException: Object reference not set to an instance of an object
Score.Update () (at Assets/Scripts/Score.cs:12)
Also I cannot put an object in the inspector even though I declared TextElement as public.
UiDocumentController.cs
using UnityEngine;
using UnityEngine.UIElements;
public class UiDocumentController : MonoBehaviour
{
[SerializeField] UIDocument _uiDocument = null;
Label _timer;
void OnEnable ()
{
OnBind( _uiDocument.rootVisualElement );
}
void Update ()
{
_timer.text = $"Time.time: {Time.time:0.00}";
}
void OnBind ( VisualElement root )
{
_timer = root.Q<Label>("timer");
}
}
-
Add UIDocument component, make sure it’s Source Asset
field is filled with an UXML
file you built
-
Add UiDocumentController
component (src above) and fill it’s UiDocument
field
-
Edit UiDocumentController
so it does what you need and that Q<Label>( ELEMENT NAME )
exist in the uxml file