Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity C# : Camera.main returns null? [duplicate]

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

like image 705
Job_September_2020 Avatar asked Mar 02 '17 10:03

Job_September_2020


2 Answers

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

like image 75
Na-Ra-Ku Avatar answered Nov 08 '22 16:11

Na-Ra-Ku


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.

like image 17
Mr.Bigglesworth Avatar answered Nov 08 '22 16:11

Mr.Bigglesworth