Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Object reference not set to an instance of an object

Henrique_S_RHenrique_S_R Member
edited June 2020 in Programming

I'm making an inventory and pick up system. When i click on the item that i want to pick up, it gives me this error:

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

PickUpItem.OnMouseOver () (at Assets/Scripts/PickUpItem.cs:33)

UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

How do i fix this? Someone, please help.


Pick up script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;


public class PickUpItem : MonoBehaviour

{

  Inventory inventoryScript;


  public float range;

  public Transform player;

  public GameObject itemIcon;


  // Start is called before the first frame update

  void Start()

  {

     

  }


  // Update is called once per frame

  void Update()

  {

     

  }


  public void OnMouseOver()

  {

    if ((player.position - gameObject.transform.position).magnitude < range)

    {

      if (Input.GetMouseButtonDown(0))

      {

        GameObject i = Instantiate(itemIcon);

        i.transform.SetParent(inventoryScript.inventoryUI.transform);

        UnityEngine.Debug.Log("Picked up " + name);

        Destroy(this.gameObject);

      }

    }

  }

}

And this is the Inventory script:

using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class Inventory : MonoBehaviour

{

  public GameObject inventoryUI;


  // Start is called before the first frame update

  void Start()

  {

     

  }


  // Update is called once per frame

  void Update()

  {

    if (Input.GetKey(KeyCode.E))

    {

      inventoryUI.SetActive(true);

    }

    else

    {

      inventoryUI.SetActive(false);

    }

  }

}

Answers

  • I've fixed it. Just had to write this in the start function:

    inventoryScript = GameObject.FindWithTag("GameController").GetComponent<Inventory>();

    and set the event system tag to "GameController".

Sign In or Register to comment.