I am using unity
I am trying to destroy a gameObject in Unity, and once that gameObject is destroyed, It adds the item to the player's inventory. The issue is, when I call this method inside Unity, I get the error:
NullReferenceException: Object reference not set to an instance of an object
all of the gameObject destruction is handled in my Character script under this method:
void PlayerInput()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Vector3 c = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit2D = Physics2D.Raycast(transform.position, c - transform.position);
if (hit2D.collider.gameObject != null)
{
int TileID = hit2D.collider.gameObject.GetComponent<IDScript>().ObjectID;
//inventory.AddItem(TileID);
Destroy(hit2D.collider.gameObject);
}
}
}
my issue arises once I remove the comment from inventory.AddItem(TileID); and try to run it. here is the method AddItem:
public void AddItem(int id)
{
Item itemToAdd = database.FetchItemByID(id);
for (int i = 0; i < Items.Count; i++)
{
if (Items[i].ID == -1)
{
Items[i] = itemToAdd;
GameObject itemObj = Instantiate(inventoryItem);
itemObj.transform.SetParent(slots[i].transform);
itemObj.transform.position = Vector2.zero;
itemObj.GetComponent<Image>().sprite = itemToAdd.Sprite;
itemObj.name = itemToAdd.Title;
break;
}
}
}
I did a little bit of debugging, and found that when I run Debug.Log(Inventory); in my Character class, the Inventory class returns null. here is the code I use to "introduce" my Inventory class to the character class:
Inventory inventory;
void Start()
{
inventory = GetComponent<Inventory>();
}
Again, I am horribly sorry if this is an easily fixable issue or something that can be found with a search query. I have searched for a good while and nothing seems to be helpful. I'm probably doing something wrong, but if I need to provide the full code I am more than willing. sorry for the long question. Thanks!