"object reference not set to an instance of an object"

im trying to make an object follow the cursor, I did this before and it worked, but now it just doesnt work, im using this code, any ideas of what is happening?

using System.Collections;
using UnityEngine;

public class click : MonoBehaviour
{
   private Vector3 mousePosition;
    public float moveSpeed = 0.1f;

    void Start()
    {
        //to prevent that object will move to zero at beginn.
        mousePosition = transform.position;
    }
    void Update()
    {
            mousePosition = Input.mousePosition;
            mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
            transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
       
    }
}

Which object is not set to an instance? And consider renaming your class as ā€œclickā€ is a pretty bad choice.

1 Like

Double-click on the error. It will open the file that the error came from. It might also put the cursor at the offending line; if not, look for the line number in the console and go to that line.

Something in that line is null.

Without that information, it is very hard to tell you anything.

ā€œ2D Physicsā€ tag. :eyes:

I’m guessing you don’t have a MainCamera in your scene now, IF this is actually the script causing the error.

Otherwise, it’s ALWAYS the same three steps… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that
1 Like

aaaaaaaaaaaaaahh, so thats whats wrong, thank you!