18

There is a free sample of C# code to move an object to a mouse click position in Unity 3D as shown below:

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;
        }
    }
}

==============

The problem is that at run time, Unity generates an error at the line:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

The error message is: NullReferenceException: Object reference not set to an instance of an object...

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. :-)

Please note that I only have 1 camera for the whole game project.

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.

enter image description here


FINAL UPDATE:

I have just found out that the stackoverflow user "Programmer" already posted an excellent answer at:

Raycast returns null

This answer fixed my issue when I use his code "GameObject.Find("NameOfCameraGameObject").GetComponent();"

So, I agree that my question above is kind of duplicated. However, when I asked if I should delete my question, the user "Programmer" 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 "Programmer" above).

My conclusion: 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 "Programmer" to fix the issue.

Big thanks to the user "Programmer" and other great stackoverflow users for helping me with this question. :-)

Job_September_2020
  • 858
  • 2
  • 10
  • 25
  • 2
    Do you have camera with main camera tag? – maximelian1986 Mar 02 '17 at 10:41
  • @maximelian1986: Yes, I do have a camera with the tag "Main Camera". What should I do next ? How do I use that "Main Camera" tag in the code sample above ? (Sorry, I am a new Unity developer with zero experience :-) – Job_September_2020 Mar 02 '17 at 10:49
  • 1
    Just add `Debug.Log(Camera.main == null);` before using it and check the result – mrogal.ski Mar 02 '17 at 10:52
  • If you have tag then it is not the issue, because it should find that camera.main – maximelian1986 Mar 02 '17 at 10:53
  • @m.rogalski: I did what you suggested, and the code says that the CAMERA is NULL. So, that is the problem. How do I fix that ? Thanks. – Job_September_2020 Mar 02 '17 at 11:01
  • 1
    You fix this by specifying one of your `Camera`s as [main camera](https://docs.unity3d.com/ScriptReference/Camera-main.html) – mrogal.ski Mar 02 '17 at 11:05
  • 1
    https://docs.unity3d.com/ScriptReference/Camera-main.html and make sure that you have only one object with that tag – maximelian1986 Mar 02 '17 at 11:07
  • @maximelian1986: As you can see from my attached image, the camera was already tagged "Main Camera", and it still crashes. I only have 1 camera for the whole game project. Should I change that tag to "Camera Main" instead ? – Job_September_2020 Mar 02 '17 at 11:21
  • No, MainCamera is correct. Make Camera type variable and assign(drag and drop ) it in scene. Then use that variable and not Camera.main. – maximelian1986 Mar 02 '17 at 11:33
  • 2
    It's not tagged, you named it `Main Camera`... But it's Tag is `Player` – mrogal.ski Mar 02 '17 at 11:36
  • 1
    It's been asked several times. That's the only one I could fine from search bar. You get null exception while trying to do use the camera for raycast or for converting to different coordinates(for example, screen to world). The answers in the duplicated questions shows ways to fix it with code other than using tag. – Programmer Mar 02 '17 at 12:02
  • @Programmer: Yes, I have just seen your answer to that question asked previously by someone else... I like your solution, and let me try your code to see if it fixes my issue... I will close my question if your solution works for my case... Let my try first. Thank you. :-) – Job_September_2020 Mar 02 '17 at 12:04
  • Also, your title is wrong. It is **not** crashing. "Error Pause" is simply enabled and you can disable that. If you are %100 percent sure that `Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);` is the problem then tagging is the problem. If the tag solution did not fix it then use the code solution I left and put the name of Camera GameObject inside the `GameObject.Find` function. – Programmer Mar 02 '17 at 12:05
  • @Programmer: As you can see in the attached image on my question, at the top of that image, the tag is automatically set to "MainCamera" by Unity, and the code still crashes. So, I will have to try your new code "GameObject.Find(....)" and see if it works. Give me a few minutes to try that out... – Job_September_2020 Mar 02 '17 at 12:11
  • I tried your solution "GameObject.Find()". The good news is that the camera is found and the code does not crash. But, there is still bad news (and that is not related to your code). First, let me tell you that I try to use that code for Unity "Roll a Ball" sample, and the bad news is that the game behaves incorrectly as follow: when I click the mouse to move the ball, I can see that the ball does not move, but the whole table (or background) along with the 4 walls and the cubes are lifted upward and then disappear from the view... So, maybe, I need to open a new question for that new issue ? – Job_September_2020 Mar 02 '17 at 12:28
  • 1
    Yes I would. Just make sure you have assigned the right objects to the right scripts. Sounds like that might be the problem. – Mr.Bigglesworth Mar 02 '17 at 12:30
  • @Mr.Bigglesworth : Yes, I will definitely open a new question for the new issue. Thanks for your help. :-) – Job_September_2020 Mar 02 '17 at 12:36
  • Yeah. I suggest you open a new question. Put your code and every information required to replicate your problem. One correction for you: Your code is not crashing. Unity is pausing execution when there is an exception. You can disable that by clicking on **Error Pause** but it is not crashing. It is simply pausing your program. – Programmer Mar 02 '17 at 12:41
  • @Programmer: Thanks. BTW, that initial "NullReferenceException" error would eventually cause the game to crash in real time if I did not fix it with your solution and play that in the real game. Is it true ? So, that was what I meant by saying that the initial code cause the game to crash. But, I can also change the title to Error Pause too. Thanks. :-) – Job_September_2020 Mar 02 '17 at 12:46
  • "Is it true ?" Nope. It won't crash. I use to think the-same before. You program will just behave weirdly. Mono has some ways to handle that . – Programmer Mar 02 '17 at 12:56
  • thanks mate, nice question/answer/collab – Alejandro Teixeira Muñoz Jan 11 '21 at 10:35

2 Answers2

23

Tag your camera as "MainCamera" https://docs.unity3d.com/ScriptReference/Camera-main.html

Na-Ra-Ku
  • 247
  • 1
  • 3
  • As you can see from my attached image, the camera was already tagged "Main Camera", and it still crashes. I only have 1 camera for the whole game project. Should I change that tag to "Camera Main" instead ? – Job_September_2020 Mar 02 '17 at 11:25
  • The strange is that I have two scripts, one working and the 2nd one return null, which confuses me – VectorX Nov 24 '19 at 11:56
17

No you have named the gameobject main camera. Tag the gameobject as main camera (below the name, currently player).

enter image description here

This is a drop down menu with some default tags and Main Camera is one of them.

Mr.Bigglesworth
  • 924
  • 9
  • 22