Hi I was looking for a script to make an object follow the cursor And very time I look for a script to make a object follow the cursor, I always find something like this: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseMove2D : MonoBehaviour { private Vector3 mousePosition; public float moveSpeed = 0.1f; void Update() { if (Input.GetButtonDown("Fire1")) { mousePosition = Input.mousePosition; mousePosition = Camera.main.ScreenToWorldPoint(mousePosition); transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed); } } } But whenever I use the script, the game crashes and it gives me this error: NullReferenceException: Object reference not set to an instance of an object MouseMove2D.Update () (at Assets/Scripts/MouseMove2D.cs:15) Any help is appreciated
Does a main camera exist in the scene? Camera.main is a shorthand for GameObject.FindWithTag("Main Camera");. Ensure you have a Camera attached to a GameObject with the tag "Main Camera" in your scene. Also, because Camera.main is a FindWithTag() call, you don't want to be calling it every frame. Cache the reference instead: Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseMove2D : MonoBehaviour { private Vector3 mousePosition; public float moveSpeed = 0.1f; private Camera mainCamera; void Start() { mainCamera = Camera.main; } void Update() { if (Input.GetButtonDown("Fire1")) { mousePosition = Input.mousePosition; mousePosition = mainCamera.ScreenToWorldPoint(mousePosition); transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed); } } }
Ok. Thanks for your tip. Managed to solve the issue. Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseMove2D : MonoBehaviour { private Vector3 mousePosition; public float moveSpeed = 0.1f; public Camera mainCamera; void Update() { mousePosition = Input.mousePosition; mousePosition = mainCamera.ScreenToWorldPoint(mousePosition); transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed); } } Thanks again!!