Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Resolved void Update() Not Recognizing Changed Variable

Discussion in 'Scripting' started by Norteous3, May 29, 2023.

  1. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    I have been working on a script that should control the pressure and temperature of a reactor in my game. I have a Power boolean that changes when a button is clicked. I also have void Update() controlling what happens if the Power boolean is true or false. While I have confirmed that the boolean is changing, Update() does not seem to recognize the change. Does anyone know how to fix this?

    Full Code (Sorry for any stupid mistakes, I am still decently new to Unity):

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using TMPro;
    5.  
    6. public class ReactorControl : MonoBehaviour
    7. {
    8.     public int ReactorTemp = 9000;
    9.     public int ReactorPSI = 12;
    10.     bool CoolantOn = false;
    11.     bool PressureRelief = false;
    12.     bool Power = false;
    13.     string Status = "STABLE";
    14.     string CoolantStatus = "OFFLINE";
    15.     string PressureReliefStatus = "OFFLINE";
    16.  
    17.     [SerializeField] GameObject TempText;
    18.     [SerializeField] GameObject PSIText;
    19.     [SerializeField] GameObject StatusScreen;
    20.     [SerializeField] GameObject StatusScreenText;
    21.     [SerializeField] GameObject Screen;
    22.     [SerializeField] GameObject PressureReliefText;
    23.     [SerializeField] GameObject CoolantText;
    24.     [SerializeField] GameObject InvisPanel;
    25.  
    26.     [SerializeField] Material BlankScreen;
    27.     [SerializeField] Material ChamberCamera;
    28.     [SerializeField] Material StatusMaterial;
    29.  
    30.  
    31.     void Start()
    32.     {
    33.         StartCoroutine(waiterTemp());
    34.         StartCoroutine(waiterPSI());
    35.     }
    36.     void Update()
    37.     {
    38.         Debug.Log("Power:" + Power);
    39.         if (Power == true)
    40.         {
    41.         TempText.GetComponent<TextMeshPro>().text = ReactorTemp.ToString() + "° K";
    42.         PSIText.GetComponent<TextMeshPro>().text = ReactorPSI.ToString() + " PSI";
    43.         StatusScreenText.GetComponent<TextMeshPro>().text = "Reactor Systems" + "\n" + "are" + "\n" + "currently:" + "\n" + Status;
    44.         CoolantText.GetComponent<TextMeshPro>().text = "Coolant Pumps: " + CoolantStatus;
    45.         PressureReliefText.GetComponent<TextMeshPro>().text = "Pressure Relief: " + PressureReliefStatus;
    46.         Screen.GetComponent<MeshRenderer>().material = ChamberCamera;
    47.         StatusScreen.GetComponent<MeshRenderer>().material = StatusMaterial;
    48.         InvisPanel.SetActive(false);
    49.         }
    50.         if (Power == false)
    51.         {
    52.         TempText.GetComponent<TextMeshPro>().text = "";
    53.         PSIText.GetComponent<TextMeshPro>().text = "";
    54.         StatusScreenText.GetComponent<TextMeshPro>().text = "";
    55.         CoolantText.GetComponent<TextMeshPro>().text = "";
    56.         PressureReliefText.GetComponent<TextMeshPro>().text = "";
    57.         Screen.GetComponent<MeshRenderer>().material = BlankScreen;
    58.         StatusScreen.GetComponent<MeshRenderer>().material = BlankScreen;
    59.         InvisPanel.SetActive(true);
    60.         }
    61.  
    62.         if (CoolantOn == true)
    63.         {
    64.             CoolantStatus = "ONLINE";
    65.         }
    66.         else
    67.         {
    68.             CoolantStatus = "OFFLINE";
    69.         }
    70.  
    71.         if (PressureRelief == true)
    72.         {
    73.             PressureReliefStatus = "ONLINE";
    74.         }
    75.         else
    76.         {
    77.             PressureReliefStatus = "OFFLINE";
    78.         }
    79.  
    80.         if (ReactorTemp > 12000)
    81.         {
    82.             Debug.Log("Explosion");
    83.         }
    84.  
    85.         if (ReactorTemp > 10000 || ReactorPSI > 21)
    86.         {
    87.             StatusScreenText.GetComponent<TextMeshPro>().color = new Color(255, 50, 0);
    88.             Status = "UNSTABLE";
    89.         }
    90.  
    91.         if (ReactorTemp > 11000)
    92.         {
    93.             StatusScreenText.GetComponent<TextMeshPro>().color = Color.red;
    94.             Status = "CRITICAL";
    95.         }
    96.  
    97.         if (ReactorTemp > 11500)
    98.         {
    99.             StatusScreenText.GetComponent<TextMeshPro>().color = new Color(255, 0, 24);
    100.             Status = "THERMAL" + "\n" + "RUNAWAY";
    101.         }
    102.     }
    103.  
    104.  
    105.     IEnumerator waiterTemp()
    106.     {
    107.         while(true)
    108.         {
    109.         yield return new WaitForSeconds(3);
    110.         //Standard temperature rise
    111.         if (ReactorPSI > 30 || ReactorTemp > 10000)
    112.         {
    113.             ReactorTemp = ReactorTemp + 120;
    114.         }
    115.         else
    116.         {
    117.         ReactorTemp = ReactorTemp + 60;
    118.         }
    119.         //If coolant on
    120.         if (CoolantOn == true)
    121.         {
    122.             ReactorTemp = ReactorTemp - 70;
    123.         }
    124.         }
    125.     }
    126.  
    127.     IEnumerator waiterPSI()
    128.     {
    129.         while(true)
    130.         {
    131.         yield return new WaitForSeconds(6);
    132.         //Standard pressure rise
    133.         if (ReactorPSI > 30 || ReactorTemp > 10000)
    134.         {
    135.             ReactorPSI = ReactorPSI + 2;
    136.         }
    137.         else
    138.         {
    139.             ReactorPSI = ReactorPSI + 1;
    140.         }
    141.             //If pressure relief on
    142.         if (PressureRelief == true)
    143.         {
    144.             ReactorTemp = ReactorTemp - 100;
    145.             ReactorPSI = ReactorPSI - 2;
    146.         }
    147.         }
    148.     }
    149.  
    150.     public void PowerToggle()
    151.     {
    152.         Power = !Power;
    153.         Debug.Log("Power: " + Power, this);
    154.     }
    155.  
    156.     public void CoolantToggle()
    157.     {
    158.         CoolantOn = !CoolantOn;
    159.         Debug.Log("Coolant: " + CoolantOn, this);
    160.     }
    161.  
    162.     public void PressureReliefToggle()
    163.     {
    164.         PressureRelief = !PressureRelief;
    165.         Debug.Log("Pressure Relief: " + PressureRelief, this);
    166.     }
    167. }
    168.  
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Time to find out why... Time to start debugging! Here is how you can begin your exciting new debugging adventures:

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

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    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.

    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 names of the GameObjects or Components involved?
    - 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.

    Visit Google for how to see console output from builds. 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: https://forum.unity.com/threads/how-to-capturing-device-logs-on-ios.529920/ or this answer for Android: https://forum.unity.com/threads/how-to-capturing-device-logs-on-android.528680/

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    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:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

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

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,070
    The way this Update is written should flood you with debug messages.

    If you're not seeing any of this, then check whether your script is enabled (the checkmark on the script component) and whether your game object is active (the checkmark on top of its inspector).
     
  4. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    It does flood it, but for some reason for every 3 times it says the variable is false, there is 1 true when it should be. I already checked to see if there was anything resetting it but I could not find anything. So I'm not sure why it is resetting. Also the components are enabled.
     
    Last edited: May 29, 2023
  5. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,070
    Ok so that you know that the data is presented right? Can you now show what is actually modulating the values? What is the code that is actually calling the methods PowerToggle() etc.
     
  6. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    I wrote a separate script that turns a 3D GameObject into a button. It runs the code once. I can only code I can find that changes the Power boolean is PowerToggle().
     
  7. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,070
    Great. Now find all the code that calls PowerToggle(), because it also indirectly changes the Power boolean. And when you find it, make sure to test it thoroughly if you can't see what's wrong with it. If you can't do any, then share that code.
     
  8. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    The only thing that calls PowerToggle() is the button maker script, here is the code for that:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Events;
    5.  
    6. public class ButtonMaker : MonoBehaviour
    7. {
    8.     public UnityEvent unityEvent = new UnityEvent();
    9.     private GameObject button;
    10.     void Start()
    11.     {
    12.         button = this.gameObject;
    13.     }
    14.  
    15.     void Update()
    16.     {
    17.         Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    18.         RaycastHit hit;
    19.         if (Input.GetMouseButtonDown(0))
    20.         {
    21.             if (Physics.Raycast(ray,out hit) && hit.collider.gameObject == gameObject)
    22.             {
    23.                 unityEvent.Invoke();
    24.             }
    25.         }
    26.     }
    27. }
    28.  
     
  9. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,070
    Okay, now you have a job to do the following:

    1) Disable all Debug.Log calls in your code by commenting them out. You can probably search and replace
    Debug.L
    with
    // Debug.L


    2) Introduce one Debug.Log call in the last code you showed, like this
    Code (csharp):
    1. if (Physics.Raycast(ray,out hit) && hit.collider.gameObject == gameObject)
    2. {
    3.   Debug.Log("button pressed");
    4.   unityEvent.Invoke();
    5. }
    3) Next, change the line that says
    Code (csharp):
    1. bool Power = false;
    into this
    Code (csharp):
    1. bool _power = false;
    2.  
    3. bool Power {
    4.   get => _power;
    5.   set {
    6.     Debug.Log($"Power has been set to {value}");
    7.     _power = value;
    8.   }
    9. }
    Turn off 'collapse' in your console, try this and tell me what's going on. Even better, show me a screenshot.
     
    Bunny83 likes this.
  10. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    This is what it gave me:

    UnityConsoleLogDebugs.png
     
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    This is known as a Debugging Air Strike.

    OP: don't try one thing and report "dudn't work..." You need to keep dicing and slicing and testing and changing and ripping and tearing and shredding until you figure out what is going on.

    Remember: we don't know either.

    When working with this, ALWAYS use source control so you can fearlessly wreck your codebase and project and then instantly restore it all with a single click once you find the problem.
     
    orionsyndrome likes this.
  12. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,070
    Okay, this looks like it's working properly. Now try to find a point of failure.
     
  13. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    I have made almost everything a comment other than these lines of code:

    Code (CSharp):
    1. bool Power = false;
    Code (CSharp):
    1. Debug.Log("Power:" + Power);
    Code (CSharp):
    1. public void PowerToggle()
    2.     {
    3.         Power = !Power;
    4.     }
    I think that it would have to be the PowerToggle(), but we already made sure it was only running once.
     
  14. Norteous3

    Norteous3

    Joined:
    Jan 2, 2023
    Posts:
    16
    Found the solution, for some reason setting the Power boolean to public and static fixed the issue and now it is working fine. Thank you for the help!
     
  15. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    20,965
    Setting a variable to static means that there is now only one copy of that variable across all instances of that class. If that fixed the problem that means you have multiple copies of that class in your scene somewhere. Which means you haven't fixed the problem merely duct taped it. So, no, it isn't actually working fine yet.
     
    Last edited: May 31, 2023
    Nad_B and Chubzdoomer like this.