Issues with Trigger for Dialogue

I’m currently trying to make dialogue boxes and I ran into an issue where the box only pops up in about 1 in 5 button presses. I’m not sure if it is an issue with my script or if OnTriggerStay works in a weird way I don’t know. And yes, my rigid body is set to always awake.

Here is the code for the UI and Box

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogueManager : MonoBehaviour
{
    public GameObject dBox;
    public Text dText;
    public bool dActive;


    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        if(dActive && (Input.GetButtonDown("Advance") || Input.GetButtonDown("Back")))
        {
            dBox.SetActive(false);
            dActive = false;
        }
    }

    public void ShowBox(string dialogue)
    {
        dActive = true;
        dBox.SetActive(true);
        dText.text = dialogue;

    }

}

Here is the code that I put in my NPC’s trigger area

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;

public class DialogueHolder : MonoBehaviour
{
    public string dialogue;
    private DialogueManager dMan;

    // Start is called before the first frame update
    void Start()
    {
        dMan = FindObjectOfType<DialogueManager>();
    }

    // Update is called once per frame
    void Update()
    {
       
    }

    private void OnTriggerStay2D(Collider2D other)
    {
        if(other.gameObject.name == "Player")
        {
            if (Input.GetButtonUp("Advance"))
            {
                dMan.ShowBox(dialogue);
            }
        }
    }
}

Throw in some Debug.Logs to see where things are going wonky. If i had to guess it is likely something to do with doing GetButtonDown and also GetButtonUp with the “Advance” button.

I’ll try that. I didn’t want to make them both Down because it just opened and immediately closed it. I’ll try and put a timer of like 5 frames to prevent that if I can’t figure it out

Hi @SuccessFail

“I’m currently trying to make dialogue boxes and I ran into an issue where the box only pops up in about 1 in 5 button presses.”

I think OnTriggerStay2D and other collision methods will run in similar pace as FixedUpdate, so you are not going to get keys detected in every Update. Add some boolean and toggle it in OnTriggerEnter and Exit and then check your key press in Update if that boolean is true.

2 Likes