Hi. I followed the course, and double checked the code as well. But when I try to test it in the game, the text in the Irate Guard dialogue is not updating. There is a “NullReferenceException: Object reference not set to an instance of an object” error in the Console as shown below.
Any help to solve this issues would be appreciated. Thank you!
Please fine below the code for the DialogueUI.cs script. Thanks in advance for your help!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using RPG.Dialogue;
using TMPro;
using UnityEngine.UI;
namespace RPG.UI
{
public class DialogueUI : MonoBehaviour
{
PlayerConversant playerConversant;
[SerializeField] TextMeshProUGUI AIText;
[SerializeField] Button nextButton;
[SerializeField] Transform choiceRoot;
[SerializeField] GameObject choicePrefab;
// Start is called before the first frame update
void Start()
{
playerConversant = GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerConversant>();
nextButton.onClick.AddListener(Next);
UpdateUI();
}
void Next()
{
playerConversant.Next();
UpdateUI();
}
void UpdateUI()
{
AIText.text = playerConversant.GetText();
nextButton.gameObject.SetActive(playerConversant.HasNext());
choiceRoot.DetachChildren();
foreach (string choiceText in playerConversant.GetChoices())
{
GameObject choiceInstance = Instantiate(choicePrefab, choiceRoot);
var textComp = choiceInstance.GetComponentInChildren<TextMeshProUGUI>();
textComp.text = choiceText;
}
}
}
}
Please fine below the code for the PlayerConversant.cs script. Thanks in advance for your help!
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace RPG.Dialogue
{
public class PlayerConversant : MonoBehaviour
{
[SerializeField] Dialogue currentDialogue;
DialogueNode currentNode = null;
private void Awake()
{
currentNode = currentDialogue.GetRootNode();
}
public string GetText()
{
if (currentNode == null)
{
return "";
}
return currentNode.GetText();
}
public IEnumerable<string> GetChoices()
{
yield return "I've lived here all my life!";
yield return "I came here from Newton.";
}
public void Next()
{
DialogueNode[] children = currentDialogue.GetAllChildren(currentNode).ToArray();
int randomIndex = Random.Range(0, children.Count());
currentNode = children[randomIndex];
}
public bool HasNext()
{
return currentDialogue.GetAllChildren(currentNode).Count() > 0;
}
}
}