- Home /
 
Storing vs not storing bool during Raycast ?
Doing a raycast and I can't seem to understand why this works :
  hit.collider.gameObject.GetComponent<Activated>().active = true; 
 
               But this doesn't:
 Key = hit.collider.gameObject.GetComponent<Activated>().active;
 Key = true;
 
               The latter just doesn't change the boolean at all, but the first does.
Answer by Baste · Nov 17, 2015 at 12:33 PM
Because bools are a value type, not a reference type. Read about them here.
In essence, your Key variable stores the value of the Activated's active variable. It does not store a reference to that variable, though, you're just copying out the value.
The easiest example of this would be something like this:
 bool t = true; //bools are value types
 bool v = t; //copies the value of t
 v = false;
 Debug.Log(t); //prints true
 
               Reference types are different:
 class BoolWrapper { //Classes are reference types
     public bool value;
 }
 //later:
 BoolWrapper t = new BoolWrapper();
 t.value = true;
 BoolWrapper v = t; //copies a reference to t
 v.value = false;
 Debug.Log(t.value); //prints false
 
               Every primitive type (int, float, double, long, char, bool) and every struct (eg. Vector2, Vector3, Quaternion) is a value type, and works like this. Classes (Like MonoBehaviours) are reference types.
Hope that helps!
Fantastic ! Thank you very much for the great answer. I understand a lot better now the difference.
Your answer