0
\$\begingroup\$

I am creating a simple 2d game in Unity. I tried to make the player able to pick up objects whenever they are clicked, but I keep getting the error I mentioned.
Here are the scripts I used : (Both of them are attached to the same object that the player wants to pick up)

First :

    public class Select : MonoBehaviour
    {
        public GameObject selectionBox;
        public bool isSelected;

        void Start()
        {
            selectionBox.SetActive(false);
        }

        void OnMouseOver()
        {
            Vector2 pos = transform.position;

            selectionBox.transform.position = pos;
            selectionBox.SetActive(true);
            isSelected = true;
        }

        void OnMouseExit()
        {
            selectionBox.SetActive(false);
            isSelected = false;
        }
    }

Second : (that gives the error)

    public class Pickup : MonoBehaviour
    {
        private Select select;
        private Inventory inventory;

        void Update()
        {
            OnMouseDown();
        }

        void OnMouseDown()
        {
            if (select.isSelected && Input.GetMouseButtonDown(0)) //Error here
                print("Click!");
        }
    }

Can anyone please tell me why I am getting this error? And how can I fix it?

Here is the error :
Object reference not set to an instance of an object Pickup.OnMouseDown () (at Pickup.cs:17)

\$\endgroup\$
4
  • \$\begingroup\$ Where do you populate the variable called select? \$\endgroup\$
    – DMGregory
    Apr 2 '20 at 21:02
  • \$\begingroup\$ What do you mean by populate the variable? \$\endgroup\$
    – PhoenXHO
    Apr 2 '20 at 21:10
  • \$\begingroup\$ Put a value into the bucket. It will usually look like select = foo; where "foo" is some expression that fetches or creates the Select object that you want to reference with this variable. Without this step, the select variable defaults to holding a value of null, which means "nothing", and you can't read the .isSelected property of nothingness — it doesn't have such a property, it's just nothing! \$\endgroup\$
    – DMGregory
    Apr 2 '20 at 21:55
  • \$\begingroup\$ @DMGregory Thanks! But I fixed it. \$\endgroup\$
    – PhoenXHO
    Apr 4 '20 at 13:28

Browse other questions tagged .