- Home /
ScreenPointToRay(Input.mouseposition) throws nullreferenceexeption
Hello, in my code here:
using UnityEngine;
using System.Collections;
public class rotatetomouse : MonoBehaviour {
public float speed = 10;
// Update is called once per frame
void Update () {
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);
float hitdist = 0;
if(playerPlane.Raycast(ray, out hitdist)){
Vector3 targetPoint = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
}
line 13: Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition); throws nullreferenceexeptions about 1/3 of the time
this is the error
NullReferenceException
UnityEngine.Camera.ScreenPointToRay (Vector3 position) (at C:/BuildAgent/work/7535de4ca26c26ac/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:376)
rotatetomouse.Update () (at Assets/scripts/rotatetomouse.cs:13)
i personally have no idea what would be causing this, since it isnt doing it all the time i have googled around a bit for the problem but everybody else that was getting errors in this kind of statement was replaceing Camera.current.ScreenPointToRay(Input.mousePosition); with Camera.main.ScreenPointToRay(Input.mousePosition); and they didnt have a "MainCamera" in their scene
sorry, i already fixed it, i fixed it by acctually making a main camera and using that ins$$anonymous$$d, i still find it weird that the Camera.current would be returning null when the screen is clicked though
Well Spotted, it seems it's a small bug/oversight in the unity camera code.i have the same issue, it means you cant use screentopoint with 2 different cameras? perhaps i have to switch off one camera when i use the other.... yes i have to :)
Answer by smokegun · Apr 20, 2014 at 10:40 AM
I had the same problem.
give the tag "MainCamera" to your camera!
Omg you made me Feel stupid. $$anonymous$$y rotation finally works! Thank You.
Thank you. I know its been 2 years since u posted this answer but you have answered my question. I have spent about an hour trying to figure out the problem.
4 years haha.
But sure no problem guys! @Ranger_Dovefalcan @Leekss