title: unity raycast , on raycast leave , how to ? c#
body: <p>i have a problem understanding how to keep a reference to an object that has previously been hit by a raycast .</p>
  
  <p>for example i can have a raycast script put on the camera of my 1rst person controller going from the camera position to the forwad vector * some value </p>
  
  <p>this script is attached to the camera </p>
  
  <pre><code>public class raycast : MonoBehaviour {
  float lenthRay = 10.0f;
  Vector3 originePos;
  Vector3 dir;
  RaycastHit hitinfo;
  GameObject hitten;
  bool isHitting;
  Color beforC;
  int selectionLayer = 9;
  
  void Update () {
      originePos = Camera.main.transform.position;
      dir = Camera.main.transform.forward * lenthRay;
      Debug.DrawRay(originePos, dir, Color.blue);
  
      if (Physics.Raycast(originePos, dir, out hitinfo, lenthRay , selectionLayer)) {
          hitten = hitinfo.transform.gameObject;
          MeshRenderer tmp = hitten.transform.GetComponent&lt;MeshRenderer&gt; ();
          beforC = tmp.material.color;
          tmp.material.color = Color.black;
      } 
      //hitten.transform.GetComponent&lt;MeshRenderer&gt; ().material.color = beforC;
      print(hitten.name);
  }
  </code></pre>
  
  <p>}</p>
  
  <p>it is working great , except if i try to access the GameObject Hitten outside my if condition (like the print <code>print(hitten.name)</code>)</p>
  
  <p>i get this error before hitting an object from the right layer :</p>
  
  <pre><code>NullReferenceException: Object reference not set to an instance of an object
  raycast.Update () (at Assets/raycast.cs:30)
  </code></pre>
  
  <p>then when i hit the object it is ok </p>
  
  <p>but the problem is , i dont understand how i can change back the object color to its original color <code>(beforC)</code> after turning it to <code>Color.black</code> when the ray exit the object </p>
  
  <p>this is what i try to do in the commented line , but i just get the same error than with the print , and nothing is turning black .</p>
  
  <p>i have tried this :</p>
  
  <pre><code>originePos = Camera.main.transform.position;
      dir = Camera.main.transform.forward * lenthRay;
      Debug.DrawRay(originePos, dir, Color.blue);
      isHitting = Physics.Raycast (originePos, dir, out hitinfo, lenthRay, selectionLayer);
      if (isHitting) {
          hitten = hitinfo.transform.gameObject;
          MeshRenderer tmp = hitten.transform.GetComponent&lt;MeshRenderer&gt; ();
          beforC = tmp.material.color;
          tmp.material.color = Color.black;
  
      } 
      if(!isHitting){
          hitten.transform.GetComponent&lt;MeshRenderer&gt; ().material.color = beforC;
          print(hitten.name);
      }
  </code></pre>
  
  <p>but it is not working either </p>
  
  <p>can you help me understand the logic i should be using 
  thanks in advance </p>