Track to mouse problems

I need an object to always face the mouse pointer and I found the following code on a scripting site. However I’m getting the error:

“NullReferenceException: Object reference not set to an instance of an object”

Does anyone know what I can do to fix this? Any help is appriciated.

P.S. I’m a noob to programming.

var speed = 4.0;

function Update () {
    var playerPlane = new Plane(Vector3.up,transform.position);
    
    var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    
    var hitdist = 0.0;
    if (playerPlane.Raycast (ray, hitdist)) {
        var targetPoint = ray.GetPoint(hitdist);
        
        var targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
        
        
        transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
    }
}

Try this:

c#

using UnityEngine;

public class LookAtExample : MonoBehaviour 
{

    public int zValue = 3;
    private Vector3 lookAtPos;	
    
	void Update () {

        Vector3 mousePos = Input.mousePosition;
        lookAtPos = Camera.main.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, zValue));
        transform.LookAt(lookAtPos);

	}

    void OnDrawGizmos()
    {
        Gizmos.DrawSphere(lookAtPos, 0.2f);
    }


}

Remember using gizmos are a great way visualize this stuff.

P.S I’m a complete noob at this too :slight_smile:

I tried the scirpt you suggested and I’m still coming up with the same NRE error. It’s probably something really simple that I’m doing wrong…I just dont know what it is.

It would help if you let us know which line pops up when you double-click on the error. It should pop to the line that’s causing the issue.

  1. Create a new project do not import any packages.
  2. Create a cube game object and position in front of the camera.
  3. Add a light to the scene.
  4. Create a new C Sharp Script called ‘LookAtExample’ and copy my code into it
  5. Attach the script to the cube

Hit play and it should be working.

Yeah it works when I start over a new project and do what you said. Wierd…why doesn’t it work on my current project?

because Unity is trying to compile all your project scripts even if you aren’t using them in the current scene. You must have errors in one of the scripts in your previous project.

Like Gargerath said if you need help you’re going to have to provide more information.

Unity should already be telling you what script and what line of code the error is occurring on.

Happy debugging :wink: