
[ad_1]
I am trying to make a dialogue system in Unity by following this tutorial: (29) 5 Minute DIALOGUE SYSTEM in UNITY Tutorial – YouTube. There is a slight twist to this and that is that I am triggering this conversation based on an event which is triggered when the boss is in sight.
However, once the conversation starts, it just prints out the letter c endlessly and goes into an infinite loop. I’ve tried looking for the cause of this problem and using a boolean flag to indicate when the characters are being “typed” but I still can’t seem to figure it out. Any help with this is much appreciated. Here is the code for the Event/Delegate class and the Dialogue class respectively:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueDelegateEvent : MonoBehaviour
{
public delegate void BossInSight(bool inSight);
public static event BossInSight OnBossInSight;
//for ending the conversation:
public delegate void ConversationComplete();
public static event ConversationComplete OnConversationComplete;
private static DialogueDelegateEvent instance;
public static DialogueDelegateEvent Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<DialogueDelegateEvent>();
}
return instance;
}
}
public void SetBossInSight()
{
OnBossInSight?.Invoke(true);
}
public void EndConversation()
{
OnConversationComplete?.Invoke();
}
}
Dialogue.cs class (class responsible for playing the dialogue lines):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Dialogue : MonoBehaviour
{
public TextMeshProUGUI textComponent;
public string[] lines;
public float textSpeed;
private int index;
private void OnEnable()
{
DialogueDelegateEvent.OnBossInSight += BeginConversation;
BeginConversation(false);
}
private void OnDisable()
{
DialogueDelegateEvent.OnBossInSight -= BeginConversation;
}
void Start()
{
textComponent.text = string.Empty;
}
private void BeginConversation(bool inSight)
{
if (inSight)
{
Time.timeScale = 0f;
StartDialogue();
}
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(textComponent.text == lines[index])
{
NextLine();
}
else
{
textComponent.text = lines[index];
StopAllCoroutines();
}
}
}
void StartDialogue()
{
index = 0;
StartCoroutine(TypeLine());
}
IEnumerator TypeLine()
{
foreach (char c in lines[index].ToCharArray())
{
textComponent.text += c;
yield return new WaitForSeconds(textSpeed);
}
}
void NextLine()
{
if (index < lines.Length - 1)
{
index++;
textComponent.text = string.Empty;
StartCoroutine(TypeLine());
}
else
{
DialogueDelegateEvent.Instance.EndConversation();
gameObject.SetActive(false);
Time.timeScale = 1f;
}
}
}
[ad_2]