- Home /
How to make an if command check a bool (or any other variable) only if it has changed
Hi
How can I make an if command that only gets activated when the bool that the if statement checks gets changed? So when the bool changes the if statement will check and see what it should do.
I was thinking about something like this:
 using UnityEngine;
 using System.Collections;
 
 public class Example : MonoBehaviour {
     
     //Variables
     private bool boolExample = false;
     private bool lastExample;
     
     // Update is called once per frame
     void Update () {
         //Here we make sure that the lastExample has the same value as boolExample
         lastExample = boolExample;
         
         if(Input.GetKeyDown(KeyCode.Space))
         {
             //Here we make it the opposite of what it already is
             boolExample = !boolExample;
         }
         
         //Here it checks if it has changed (we can do that because we haven't given  lastExample the same value as boolExample yet)
         if(boolExample != lastExample)
         {
             //Here we write the code instead of this silly message
             print("The bool has been changed by forces unknown");
         }
     }
 }
               Comment
              
 
               
               
               Best Answer 
              
 
              Answer by whydoidoit · Jun 20, 2012 at 08:20 PM
Looks good to me. The only thing is you would have to set the value of lastExample inside that if.
Your answer
 
 
             Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Making a light turn on and off with the same button 1 Answer
empty component var 1 Answer
set another scripts variable 2 Answers
How much memory does a pointer use? 5 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                