0

I am getting the following error:

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

when trying to pick object at this line:

Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));

Full code:

using UnityEngine;
using System.Collections;
public class pickupobject : 

MonoBehaviour {
    GameObject mainCamera;
    public float distance;
    GameObject carryObject;
    bool carrying;
    void start() {
        mainCamera = GameObject.FindWithTag("MainCamera");
    }

    void pickup()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            int x = Screen.width / 2;
            int y = Screen.height / 2;
            Ray ray = mainCamera.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y));
            // Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow);
            RaycastHit hit;
            if (Physics.Raycast(ray, out hit))
            {
                pickupcube p = hit.collider.GetComponent<pickupcube>();
                if (p != null)
                {
                    carrying = true;
                    carryObject = p.gameObject;
                }
            }
        }
    }

    void carry(GameObject o)
    {
        o.GetComponent<Rigidbody>().isKinematic = true;
        o.transform.position = mainCamera.transform.position + mainCamera.transform.forward * distance;
    }

    // Update is called once per frame
    void Update()
    {
        if (carrying)
        {
            carry(carryObject);
        }
        else
        {
            pickup();
        }
    }

}
Olivier Moindrot
  • 26,084
  • 11
  • 84
  • 87
Farhan Ali
  • 316
  • 2
  • 5
  • 16
  • Please Help me for that, thanks in advance – Farhan Ali Nov 18 '15 at 20:08
  • Possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Nov 19 '15 at 19:01

1 Answers1

1

Try writing the same line like this:

Ray ray = Camera.main.gameObject.GetComponent<Camera>().ScreenPointToRay(new Vector3(x, y, 0));

First of all FindWithTag and any Find is pretty expansive (doesn't matter much in your case since you call it only once but just so you know for the record), you should check the spelling there and experiment with Debug.Log(); Print to console value of mainCamera, of Ray etc... and see when you get unexpected results. For now just try my code, it's pretty much the same it only uses different reference to camera

http://docs.unity3d.com/ScriptReference/Camera-main.html

Neven Ignjic
  • 653
  • 5
  • 11