- Home /
Trigger the dialogue system
Hi there. I wrote the code which should be triggered by trigger but it works before I trigger the trigger. It's just that I think I wrote everything by logic, but apparently, I did not. Thanks in advance if you help me.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
/// <summary>
/// Simple dialogue system. No choices.
/// </summary>
public class Dialogue : MonoBehaviour
{
[SerializeField] TextMeshProUGUI theText;
[SerializeField] string[] sentences;
[SerializeField] float typeSpeed = 0.02f;
[SerializeField] GameObject continueButton;
int index;
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player" && Input.GetKeyDown(KeyCode.E))
{
StartCoroutine(StartDialogue());
}
}
private void OnTriggerExit(Collider other)
{
if(other.tag == "Player")
{
continueButton.SetActive(false);
}
}
public void NextSentence()//button func
{
continueButton.SetActive(false);
if (index < sentences.Length - 1)
{
index++;
theText.text = "";
StartCoroutine(StartDialogue());
}
else
{
theText.text = "";
continueButton.SetActive(false);
}
}
IEnumerator StartDialogue()
{
foreach (char letter in sentences[index].ToCharArray())
{
theText.text += letter;
if (theText.text == sentences[index])
{
continueButton.SetActive(true);
}
yield return new WaitForSeconds(typeSpeed);
}
}
}
Answer by Larry-Dietz · Dec 16, 2019 at 04:57 PM
Looking at your code, it looks like it would only start the coroutine if you enter the collider, AND press E in the exact same frame.
I would try moving this into OnTriggerStay. The OnEnter only fires 1 time, when you first enter the collider, on trigger stay fires repeatedly as long as you stay in the collider.
This will continue to look for your keydown event each frame, and call the coroutine when you press E as long as you are still in the collider.
Hope this helps, -Larry
Alright, will try it out . But the thing is, coroutine is started BEFORE I even enter a trigger.
That part throws me. I just tested this here, and with the change I suggested, it appeared to be working as expected. The dialog didn't start until I entered the trigger and hit $$anonymous$$ You do have this script attached to your dialog object, correct? Not the player?
Your answer
Follow this Question
Related Questions
Trigger Script Not Firing 4 Answers
I want to change TextMeshProUGUI based on value of a float, but I cant seem to work it. 0 Answers
Why does my trigger only fire one time? 0 Answers
3D Text (TextMesh) not updated/redrawn every frame (android only) 0 Answers
Picking up an Item and telling you how many you have 1 Answer