- Home /
 
Object reference not set to an instance of an object
I wanted to make my sprite rotate toward a cursor, but when I run my game, Unity is giving me this error at
"Vector3 mouseWorldSpace = Camera.main.ScreenToWorldPoint(mouseScreenPosition);". Help me, please!
That's my script:
public class PlayerMoving : MonoBehaviour {
 // Update is called once per frame
 void Update () {
     
     if (Input.GetKey (KeyCode.A)) 
         transform.Translate (new Vector3 (0, 5, 0) * Time.deltaTime);            
     
     if (Input.GetKey (KeyCode.D)) 
         transform.Translate (new Vector3 (0, -5, 0) * Time.deltaTime);
     
     if (Input.GetKey (KeyCode.W)) 
         transform.Translate (new Vector3 (5, 0, 0) * Time.deltaTime);
     
     if (Input.GetKey (KeyCode.S)) 
         transform.Translate (new Vector3 (-5, 0, 0) * Time.deltaTime);    
     Vector3 upAxis = new Vector3(0,0,-1);
     Vector3 mouseScreenPosition = Input.mousePosition;
     //set mouses z to your targets
     mouseScreenPosition.z = transform.position.z;
     Vector3 mouseWorldSpace = Camera.main.ScreenToWorldPoint(mouseScreenPosition);
     transform.LookAt(mouseWorldSpace, upAxis);
     //zero out all rotations except the axis I want
     transform.eulerAngles = new Vector3(0,0,-transform.eulerAngles.z);
 }
 
               }
What you have posted is not an error but a line of code. What's the actual error?
$$anonymous$$ay be you don't have "$$anonymous$$ain Camera" in the scene. Check if you have Camera with tag "$$anonymous$$ain Camera".
Your answer
 
             Follow this Question
Related Questions
Smoothing out rotations 1 Answer
Move the player(cube) to the enemy(cube) by clicking on enemy? 1 Answer
Move the player towards the cube to attack. 0 Answers
How can I let my Sprite look towards the mouse in Unity 4.3 2D? 1 Answer
How to make an object rotate on the y axis towards the mouse? 3 Answers