Search Unity

[HELP] Rotation in top down

Discussion in '2D' started by Hoarmurath, Mar 15, 2017.

  1. Hoarmurath

    Hoarmurath

    Joined:
    Mar 22, 2016
    Posts:
    27
    So i have a problem with player rotating to mouse and the problem is that it it doesnt work and spews out:
    NullReferenceException: Object reference not set to an instance of an object
    RotateToCursor.rotateToCamera () (at Assets/Scripts/RotateToCursor.cs:22)
    RotateToCursor.Update () (at Assets/Scripts/RotateToCursor.cs:14)

    Script:
    Code (CSharp):
    1.     Vector3 mousePos;
    2.     Rigidbody2D bod;
    3.  
    4.     // Use this for initialization
    5.     void Start () {
    6.         bod = this.GetComponent<Rigidbody2D> ();
    7.     }
    8.    
    9.     // Update is called once per frame
    10.     void Update () {
    11.         rotateToCamera ();
    12.     }
    13.  
    14.  
    15.  
    16.  
    17.     void rotateToCamera()
    18.     {
    19.         mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
    20.         Quaternion rot = Quaternion.LookRotation (transform.position - mousePos, Vector3.forward);
    21.  
    22.         transform.rotation = rot;
    23.         transform.eulerAngles = new Vector3 (0, 0, transform.eulerAngles.z);
    24.         bod.angularVelocity = 0;
    25. }
    Thanks
     
  2. mikael_juhala

    mikael_juhala

    Joined:
    Mar 9, 2015
    Posts:
    247
    You have removed part of the script, so what actually is the line 22? I would guess it's referring to the "bod" variable being null.
     
  3. Hoarmurath

    Hoarmurath

    Joined:
    Mar 22, 2016
    Posts:
    27
    line 22 is making the objects rotation = to rotation in line 20
     
  4. mikael_juhala

    mikael_juhala

    Joined:
    Mar 9, 2015
    Posts:
    247
    No, I'm asking what is on the line 22 in the actual file. Your code sample is missing pieces (the class definition for example) and the error is referring a problem on line 22 (not the line 22 in the sample, but in the file).

    Anyway, make sure your GameObject has Rigidbody2D, otherwise "bod" would be null.