Give an item to the player through the dialogue

Hello,
I was wondering, how would we give an item to the player through a specific answer in the dialogue (not related to the quest). I tried to create a script with GiveReward function that would be called through a dialogue trigger but it gives back a NullReferenceException: Object reference not set to an instance of an object. Is it because I don’t have a Getter?

using System.Collections;
using System.Collections.Generic;
using GameDevTV.Inventories;
using UnityEngine;

namespace RPG.Quests
{
    public class ItemGiver : MonoBehaviour
    {
        public InventoryItem item;
        
        public void GiveItem()
        {

            bool success = GetComponent<Inventory>().AddToFirstEmptySlot(item, 1);
            if (!success)
            {
                GetComponent<ItemDropper>().DropItem(item);
            }
        }

    }
}

Thanks in advance.

I haven’t done that course yet so I don’t know what would be your likely issue, but null reference exceptions are because you’re calling/using an object that hasn’t been set. So it could be your item, it could be a requirement from a method that you’re calling, it could be from a missing Component. The error message should point you to the right part it’s having an issue with.

You’re looking to give the player the item, but you’re looking for an Inventory on the Dialogue speaker. We want to find the inventory on the Player.
Try this instead:

Inventory playerInventory = GameObject.FindWithTag("Player").GetComponent<Inventory>().AddToFirstEmptySlot(item, 1);

So the null was that he couldn’t find the Inventory. Thank you so much!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms