This question was
closed Nov 02, 2017 at 07:48 AM by
Yukken for the following reason:
The question is answered, right answer was accepted
Question by
Yukken · Nov 02, 2017 at 06:26 AM ·
nullreferenceexceptiontransform.positiontransform.rotation
object referance not set to instance of an object when accessing transform.position
I'm trying to rotate a sprite according to mouse position.But I get an error when I hit play. I'm using transform.position to get the position of the object this script is attached to but I get an error.
I'm using the latest version of unity 5.6.
The code:
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent (typeof (playerController))]
public class controllcenter : MonoBehaviour {
public float moveSpeed = 5f;
playerController controller;
// Use this for initialization
void Start () {
controller = GetComponent<playerController>();
}
// Update is called once per frame
void Update () {
Vector3 difference = (Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position).normalized;
float angle = Mathf.Atan2(difference.y,difference.x)*Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);
Vector2 playerInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector2 moveVelocity = playerInput.normalized * moveSpeed;
controller.updateVelocity(moveVelocity);
}
Comment
To anyone having this problem,it's actually because of the camera doesn't have the maincamera tag you'll get the nullref error.