title: Unity C# : Camera.main returns null?
body: <p>There is a free sample of C# code to move an object to a mouse click position in Unity 3D as shown below:</p>
  
  <pre><code>public GameObject cube;
  Vector3 targetPosition;
  
  void Start () {
  
      targetPosition = transform.position;
  }
  void Update(){
  
      if (Input.GetMouseButtonDown(0)){
          Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
          RaycastHit hit;
  
          if (Physics.Raycast(ray, out hit)){
              targetPosition = hit.point;
              cube.transform.position = targetPosition;
          }
      }
  }
  </code></pre>
  
  <p>==============</p>
  
  <p>The problem is that at run time, Unity generates an error at the line:</p>
  
  <p><strong>Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);</strong></p>
  
  <p>The error message is:  <strong>NullReferenceException: Object reference not set to an instance of an object</strong>...</p>
  
  <p>Per someone's suggestion, I have just put some debug statements in the sample code above, and found that "Camera.main" is NULL. So, that is the main reason the Unity generates the error message above. :-)</p>
  
  <p><strong>Please note that I only have 1 camera for the whole game project.</strong></p>
  
  <p>Here is the captured image of my "Main Camera" that is already enabled and tagged as "Main Camera" automatically by Unity.  But, that does not fix the problem either.</p>
  
  <p><a href="https://i.stack.imgur.com/WuziZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WuziZ.png" alt="enter image description here"></a></p>
  
  <hr>
  
  <p><strong>FINAL UPDATE:</strong>   </p>
  
  <p>I have just found out that the stackoverflow user "<strong>Programmer</strong>" already posted an excellent answer at:</p>
  
  <p><a href="https://stackoverflow.com/questions/41659982/raycast-returns-null">Raycast returns null</a></p>
  
  <p>This answer fixed my issue when I use his code "<strong>GameObject.Find("NameOfCameraGameObject").GetComponent();</strong>"</p>
  
  <p>So, I agree that my question above is kind of duplicated.  However, when I asked if I should delete my question, the user "<strong>Programmer</strong>" suggested that I may keep this question open as it may still be useful for someone else to view in the future. (Again, I already post the link to the correct answer by user "<strong>Programmer</strong>" above).</p>
  
  <p><strong>My conclusion</strong>:  it is strange that even though Unity automatically enables the tag "MainCamera", the code still thinks that "Camera.Main" is null. Therefore, I have to use the code written by the user "<strong>Programmer</strong>" to fix the issue.</p>
  
  <p>Big thanks to the user "<strong>Programmer</strong>" and other great stackoverflow users for helping me with this question. :-)</p>