UnityEngineCameraBindings.gen.cs throwing a NullReferenceException when using the Camera.ScreenToWorldPoint() Method.
A portion of my code is supposed to convert each touches screen pixel coordinates to a Vector2 World Point (Unity transform units). When I run the script (and touch the touchscreen I have connected), I get a NullReferenceException, yet VisualStudio never reported any problems within the script that I wrote. When I checked the Error List I got this feedback: !Here's a paste able version of the code in the picture:
void Update()
{
for (int i = 0; i < Input.touches.Length; i++)
{
Camera camera = new Camera();
Vector3 worldPoint3d = camera.ScreenToWorldPoint(new Vector3(Input.touches[i].position.x,Input.touches[i].position.y,0));
Vector2 worldPoint2d = new Vector2(worldPoint3d.x, worldPoint3d.y);
}
}
The first thing I noticed was that the error was reported on line 458, while the script i'm writing currently only has 55 lines. I also noticed that it was reported in a file called "UnityEngineCameraBindings.gen.cs". The code you see in the picture does in fact use the UnityEngine.Camera.ScreenToWorldPoint() which is a Unity documented method. I may be an amateur programmer but I can deduce that the problem may not lie with my script, rather somewhere in the Camera class of the UnityEngine namespace.
I'd appreciate any suggestions on how I might be able to fix this, feedback on whether it's just me that's experiencing it or if its bug in the latest Unity update (5.3.5f1), or possibly any alternative way of scripting the function that the code in the picture performs.
Answer by btmedia14 · Jun 17, 2016 at 04:00 AM
Try changing
Camera camera = new Camera();
to
Camera camera = GetComponent<Camera>();
This will obtain the camera game object from the scene, as opposed to creating a new camera which is likely unattached to the scene.
Thanks for pointing that out. I realized that Unity does not just automatically assume that you are referring to the main camera or whichever camera is currently casting to the game view when you're asking a camera's pixel resolution to be measured and converted to transform units. As a slight alteration to your answer, I declared the $$anonymous$$ain Camera (The only one I use for this project) as a Game Object (named 'mainCamera') in the touch script and I created an instance with: Camera camera = mainCamera.GetComponent(); And everything works perfectly now.
Once again thank you for your support.