Boolean starting and staying true when its initialized as false

Hi, im doing a dialogue system and making a boolean that initializes as true even if its set to be false, when inside a trigger collider it should switch to true, but its true all the time regardless.

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

public class DialogoDaro : MonoBehaviour

{
   
    public GameObject Daro;
    public Text dialogo;
    public RawImage Cartel;
    public Image fondoNombre;
    public Text Nombre;
    public Text AvanzarDialogo;
    [SerializeField] int counter = 0;
    [SerializeField] string[] dialogoArray = new string[] {"Hola amigo!", "No sé si te enteraste, probablemennte si, pero...", "Ahora en un rato es empatizando!", "Y los meps no llegaron...", "Tengo una idea!", "Podrias ayudarme a buscar los proyectos mas importantes?", "Tengo que... ordenarlos...", "Despues, veni aca y dejalos todos apilados... Ya vas a ver","¿Porque seguis aca? Anda!" };
    [SerializeField] bool enRango = false;
    // Start is called before the first frame update
    void Start()
    {
        enRango = false;
        //initialize as false
    }

    // Update is called once per frame
    void Update()
    {
        if (enRango)
        {
            {
            if (Input.GetKeyDown(KeyCode.E) && counter <= 6)
                {  
                counter++;
                Debug.Log(counter);
                dialogo.text = dialogoArray[counter];
                } 
            }
        }
        if(counter >= 7)
        {
            AvanzarDialogo.enabled = false;
        } 
    }
    void OnTriggerEnter(Collider Daro)
    {
    if(Daro.transform.tag == "NPC"){
        if (counter >= 7)
        {
            AvanzarDialogo.enabled = false;
        }
        else
        {
            AvanzarDialogo.enabled = true;
        }
        Cartel.enabled = true;
        dialogo.enabled = true;
        fondoNombre.enabled = true;
        Nombre.enabled = true;
        Debug.Log("entraste");
    }
          
    }
    void OnTriggerStay(Collider Daro)
    {
        if(Daro.transform.tag == "NPC")
        {
            // boolean for inRange goes true
           enRango = true;
        }
       

    }
    void OnTriggerExit(Collider Daro)
    {
        if(Daro.transform.tag == "NPC")
        {
        Cartel.enabled = false;
        dialogo.enabled = false;
        fondoNombre.enabled = false;
        Nombre.enabled = false;
        AvanzarDialogo.enabled = false;
        // All text until here
        enRango = false;
        }
    }  
}

You must find a way to get the information you need in order to reason about what the problem is.

What is often happening in these cases is one of the following:

  • the code you think is executing is not actually executing at all
  • the code is executing far EARLIER or LATER than you think
  • the code is executing far LESS OFTEN than you think
  • the code is executing far MORE OFTEN than you think
  • the code is executing on another GameObject than you think it is
  • you’re getting an error or warning and you haven’t noticed it in the console window

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

In your case, I suggest a bare minimum of one Debug.Log() per location that sets the boolean.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run? what order does it run in?
  • what are the values of the variables involved? Are they initialized? Are the values reasonable?
  • are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

Knowing this information will help you reason about the behavior you are seeing.

You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as Debug.Log("Problem!",this);

If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

You could also just display various important quantities in UI Text elements to watch them change as you play the game.

If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer or iOS: How To - Capturing Device Logs on iOS or this answer for Android: How To - Capturing Device Logs on Android

Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

Here’s an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

When in doubt, print it out!™

Note: the print() function is an alias for Debug.Log() provided by the MonoBehaviour class.

Serialized properties in Unity are initialized as a cascade of possible values, each subsequent value (if present) overwriting the previous value:

  • what the class constructor makes (either default(T) or else field initializers)

  • what is saved with the prefab

  • what is saved with the prefab override(s)/variant(s)

  • what is saved in the scene and not applied to the prefab

  • what is changed in Awake(), Start(), or even later etc.

Make sure you only initialize things at ONE of the above levels, or if necessary, at levels that you specifically understand in your use case. Otherwise errors will seem very mysterious.

Field initializers versus using Reset() function and Unity serialization:

Like Kurt said, just put a Debug.Log into this part:

void OnTriggerStay(Collider Daro)
{
    if(Daro.transform.tag == "NPC")
    {
        Debug.Log($"OnTriggerStay. enRango is {enRango} and will be set to true now");
        enRango = true;
    }
}

If you see that message right from the start, it means you are already inside a trigger with that tag. The first log you see should say "OnTriggerStay. enRango is false and will be set to true now". And of course it would stay true as long as you overlap with the trigger. You can also add log messages to OnTriggerEnter / Exit to see when those are actually called.

Note that your system of checking the tag should work. However a potential pitfal could be if you change the tag dynamically. As this would not reset the bool when you leave the trigger as you would not enter the if statement in such a case.

ps: What IDE do you use to edit your code? How did you manage to mess up the indentation that much ^^. Also those extra curly braces inside the if (enRango) block are pointless and just clutters the code.

1 Like

Try Debug.Log in Update() to see when it changes, because clearly it can’t be true before or during Start().

Also I don’t think you need to set it to true in OnTriggerStay. Just do it once in OnTriggerEnter. In OnTriggerStay you’d do stuff like increase a counter each frame, but setting a variable to true is redundant.

And yes—get the formatting corrected :slight_smile: It’s not just for looks, it’s essential for seeing the structure of the code.

1 Like