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.
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. :-)
Tag your camera as "MainCamera" https://docs.unity3d.com/ScriptReference/Camera-main.html
No you have named the gameobject main camera. Tag the gameobject as main camera (below the name, currently player).
This is a drop down menu with some default tags and Main Camera is one of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With