So the code is working but when I press F key again it starts from the beginning but I want it to disappear and if the player wants to see it again to press the F key once more to see the dialogue again. I know that my mistake is in the void EndDialogue()
but I don't know how to fix it.
This is the dialogue script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Dialogue : MonoBehaviour
{
public GameObject window;
public GameObject indicator;
public TMP_Text dialogueText;
public List<string> dialogues;
public float writingSpeed;
public int index;
private int charIndex;
public bool started;
private bool waitForNext;
private void Awake()
{
ToggleIndicator(false);
ToggleWindow(false);
started = false;
}
public void ToggleWindow(bool show)
{
window.SetActive(show);
}
public void ToggleIndicator(bool show)
{
indicator.SetActive(show);
}
public void StartDialogue()
{
if (started)
return;
if (waitForNext)
return;
started = true;
ToggleWindow(true);
ToggleIndicator(true);
GetDialogue(0);
}
private void GetDialogue(int i)
{
index = i;
charIndex = 0;
dialogueText.text = string.Empty;
StartCoroutine(Writing());
}
public void EndDialogue()
{
started = false;
waitForNext = false;
StopAllCoroutines();
ToggleWindow(false);
}
IEnumerator Writing()
{
yield return new WaitForSeconds(writingSpeed);
string currentDialogue = dialogues[index];
dialogueText.text += currentDialogue[charIndex];
charIndex++;
if (charIndex < currentDialogue.Length)
{
yield return new WaitForSeconds(writingSpeed);
StartCoroutine(Writing());
}
else
{
waitForNext = true;
}
}
void Update()
{
if (!started)
return;
if (waitForNext && Input.GetKeyDown(KeyCode.F))
{
waitForNext = false;
index++;
if (index < dialogues.Count)
{
GetDialogue(index);
}
else
{
ToggleIndicator(true);
EndDialogue();
}
}
}
}
and this is the dialogue trigger script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DialogueTrigger : MonoBehaviour
{
public Dialogue dialogueScript;
private bool playerDetected;
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.tag == "Player")
{
playerDetected = true;
dialogueScript.ToggleIndicator(playerDetected);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.tag == "Player")
{
playerDetected = false;
dialogueScript.ToggleIndicator(playerDetected);
dialogueScript.EndDialogue();
}
}
private void Update()
{
if (playerDetected && Input.GetKeyDown(KeyCode.F ))
{
dialogueScript.StartDialogue();
}
}
}