Rotation while movement problem

Hello guys,

I’ve got simple movement function, which works just fine

void Move() {
	if(Mathf.Abs(Input.GetAxis("MoveForward")) > 0){

		controller.SimpleMove(myTransform.TransformDirection(Vector3.forward) * Input.GetAxis("MoveForward") * moveSpeed);

		animation.wrapMode = WrapMode.Loop;
		animation.CrossFade("run");
	}
	else {
		animation.CrossFade("idle", 0.4f);
	}
}

but I wanted to attach another for rotation, so here it is

void Rotate() {

    Plane playerPlane = new Plane(Vector3.up, transform.position);

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

    float hitdist = 0.0f;

    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, rotateSpeed * Time.time);
	}		
}

I call both in update and while just rotating or moving it works perfectly, but giving lots of that (not fot movement alone ofcourse):

NullReferenceException
UnityEngine.Camera.ScreenPointToRay (Vector3 position) (at C:/BuildAgent/work/812c4f5049264fad/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:291)
Movement.Rotate () (at Assets/Scripts/Actual Work/Movement.cs:30)
Movement.Move () (at Assets/Scripts/Actual Work/Movement.cs:48)
Movement.Update () (at Assets/Scripts/Actual Work/Movement.cs:23)

Real problem starts when I try to move and rotate in same time, my game object rotates like in steps (like 20-30 degrees at once), from time to time.

Don’t use Camera.current. It is only set in rendering callbacks. In Update it will always return null because during Update no camera is “active”. See the docs on Camera.current

So use either:

  • Camera.main
  • or if you want to use a specific camera, create a public variable of type Camera and assign the camera in the inspector.

NullReferenceException are always a problem and need to be dealt with, as any code following the line where it occurse is never executed, even if it’s unrelated to the null object.

In your case it is cause by Camera.current being null at some point, which can happen in the editor since the internal SceneView camera also messes with that variable. As the docs mention, you shouln’t generally use that.

Thanks guys, I tried to get the way around returning null when using Camera.main, because I have misread about it. I tough it uses camera ‘named’ MainCamera, but it was just about setting its tag to it.
Thanks for replies, now it works just perfect.