Search code examples
c#unity-game-engineboolean

How can I make a bool happen only once?


I'm trying to set up a dialogue system and I can't figure out how to make it stop repeating every frame.

{
    [SerializeField] public TMP_Text dialogueText;
    [SerializeField] public GameObject dialogueBox;
    public stopPlayer stopPlayer;
    public GameObject player;

    public DialogueObject currentDialogue;
    void Start()
    {
        stopPlayer = player.GetComponent<stopPlayer>();
        dialogueBox.SetActive(false);
    }
    void FixedUpdate()
    {
        if(stopPlayer.frozen)
        {
            dialogueBox.SetActive(true);
            DisplayDialogue(currentDialogue);
        }
    }
    private IEnumerator MoveThroughDialogue(DialogueObject dialogueObject)
    {
        for(int i = 0; i < dialogueObject.dialogueLines.Length; i++)
        {
            dialogueText.text = dialogueObject.dialogueLines[i].dialogue;
        
            //The following line of code makes it so that the for loop is paused until the user clicks the left mouse button.
            yield return new WaitUntil(()=>Input.GetMouseButtonDown(0));
            //The following line of codes make the coroutine wait for a frame so as the next WaitUntil is not skipped
            yield return null;
        }
        dialogueBox.SetActive(true);
    }
    
    public void DisplayDialogue(DialogueObject dialogueObject)
    {
        StartCoroutine(MoveThroughDialogue(dialogueObject));
    }
}

I needed a bool from another script, but the problem is that the dialogue function is called and repeated every frame the bool is active.

I couldn't find any answers online, and I tried to move the code around to fit the other script, but that did the same thing.


Solution

  • You are calling DisplayDialogue in FixedUpdate, which runs continuously. Either you set stopPlayer.frozen = false; after calling DisplayDialogue, or you should create a flag value to check if the dialogue was already displayed.