Hello, I’ve been stuck all day trying to make this work. I’m new to Unity, so I fully understand that this is probably a lot more complicated than it needs to be.
I have managed to make a working script where a random piece of dialogue gets chosen from an array and then gets written out on a dialogue box
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RandomJadeDialogue : MonoBehaviour
{
public GameObject dialogBox;
public bool playerInRange;
public string[] randomDialog = new string[30];
public Text selectedDialog;
void Start()
{
//(This is where all the array items are located)
}
string GetRandomDialog()
{
int random = Random.Range(0, randomDialog.Length);
return randomDialog[random];
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && playerInRange)
{
if (dialogBox.activeInHierarchy)
{
dialogBox.SetActive(false);
}
else
{
dialogBox.SetActive(true);
selectedDialog.text = GetRandomDialog();
}
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerInRange = true;
}
}
private void OnTriggerExit2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
playerInRange = false;
dialogBox.SetActive(false);
}
}
}
but I would like to make it so that the text gets typed out, like in an old rpg. The way I have attempted to this so far has been making a new script where the code for the typewriting is, and within that script I’ve tried to find a way to GetComponent<Text>().text
, but the code does not work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TypeWriterEffect : MonoBehaviour
{
public float delay = 0.1f;
public string fullText;
private string currentText = "";
void Start()
{
StartCoroutine(ShowText());
}
IEnumerator ShowText()
{
for (int i = 0; i < fullText.Length; i++)
currentText = fullText.Substring(0, i);
GetComponent<Text>().text = currentText;
yield return new WaitForSeconds(delay);
Debug.Log("reached loop");
}
}
When I try to run the game, the log tells me “NullReferenceException: Object reference not set to an instance of an object”
I believe this to be because the Text that GetComponent<Text>().text
is trying to Get starts out blank, and therefore there is no way for the program to know what text it should write out, but I’m also having a really hard time understanding how GetComponent works to begin with, so it could definitely be something else.