OnTriggerEnter/Exit Collider2d Dialogbox problem

Hey Everyone im new to C# and Unity game devoloping. İm trying to make a simple Dialogue system. When i enter Collider2D is set trigger Dialogue appears, when i Exit Dialogue disapper. İ do somewhat close to this. But not work as neded. When i enter collider Dialog box continously activated and disactivated even if i dont exit the collider. Can Someone tweak code a bit ? And Add V2 as a Destroy game object line on exit proper way ? For on the exit disabiling the box. İ cant manage the do that in working way.Here's the code lines;

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

public class DialogueSysteam : MonoBehaviour {

    public GameObject dialogBox;
    public TMP_Text dialogText;
    public string dialog;
    public bool playerInRange;

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

    }

    // Update is called once per frame
    void Update()
    {
        if(playerInRange)
        {


             if(dialogBox.activeInHierarchy){
              dialogBox.SetActive(false);
             } else{
              dialogBox.SetActive(true);
              dialogText.text = dialog;
             }
        }
    }
    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            playerInRange = true;
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            playerInRange = false;
            dialogBox.SetActive(false);
        }
    }
}

İ guess İf state broke the code ? But im not sure.

Make it more simple like this:

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

public class DialogueSystem : MonoBehaviour
{
    public GameObject dialogBox;
    public TMP_Text dialogText;
    public string dialog;
    public bool playerInRange = false;

    void Start()
    {
        dialogBox.SetActive(playerInRange);
        dialogText.text = dialog;
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            playerInRange = true;
            dialogBox.SetActive(playerInRange);
        }
    }

    private void OnTriggerExit2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            playerInRange = false;
            dialogBox.SetActive(playerInRange);
        }
    }
}
1 Like


Thanks for your help and clearing up the code.