0

Like said in the question, I can not figure out why I cannot add item to my rooms if anyone has an insight on this I would appreciate it. I'm not sure if need to somehow import dicitonary to CreateRooms( ) if yes how?

    public void CreateRooms()
    {
        // create the rooms
        Room outside = new Room("outside the main entrance of the university");
        Room hallway = new Room("inside the hallway of the university");
        Room theatre = new Room("in a lecture theatre");
        Room basement = new Room("in the basement");
        Room pub = new Room("in the campus pub");
        Room lab = new Room("in a computing lab");
        Room office = new Room("in the computing admin office");


        // initialise room exits
        outside.AddExit("east", hallway);
        outside.AddExit("south", lab);
        outside.AddExit("west", pub);

        hallway.AddExit("west", outside);
        hallway.AddExit("up", theatre);
        hallway.AddExit("down", basement);


        theatre.AddExit("down", hallway);

        basement.AddExit("up", hallway);

        pub.AddExit("east", outside);

        lab.AddExit("north", outside);
        lab.AddExit("east", office);

        office.AddExit("west", lab);

        Item axe = new Item(5, "a sharp axe");

        outside.Chest.Put("axe", axe); // System.NullReferenceException

        player.currentRoom = outside;  // start game outside
        


    }

These are the methods that put items to the room and where I get/take item from room to my inventory.

   public bool Put(string itemName, Item item)
    {          
        items.Add(itemName, item);
        Console.WriteLine("There is " + itemName + " in this room. Will you take it?");
        return true;
    }
    public Item Get(string itemName)
    {
        Item item = null;
        if (items.ContainsKey(itemName))
        {
            item = items[itemName];
            items.Remove(itemName);
        }
        return item;
    }
Mindo
  • 13
  • 3
  • The duplicate should teach you everything about NRE. Also, if you want some tips, at least tell us on which line do you get the exception. – Steve Feb 07 '22 at 11:59
  • @Steve I've added a comment on a line where I get the exception. – Mindo Feb 07 '22 at 12:03
  • So you have create the _outside_ room but do you have somewhere the code that initialize the _Chest_ property? You cannot use a reference type if you don't initialize (new) it – Steve Feb 07 '22 at 12:16

1 Answers1

0

I think your 'Chest' is null - or mabye your list in Chest - you must instantiate objects before you can use them.

OneBigQuestion
  • 149
  • 6
  • 19