-1

FOr this example, I'm using a simplified version of my code but it follow the same concept. I want to have a BookStore that has a List of Books and each Book has a List of Pages where each Page has just the data of that page

public class BookStore
{
public class Book
{
    public class Page
    {
        public string pageText;

        public Page(string newText)
        {
            pageText = newText;
        }
    }
    public List<Page> listofPages;

    public void InsertPageAt0(string newPageText)
    {
        listofPages.Insert(0, new Page(newPageText));
    }
}
public List<Book> listofBooks;

public void AddNewPage(int bookID, string pageText)
{
    listofBooks[bookID].InsertPageAt0(pageText);
}
}

THe following code is where I try to populate the list:

BookStore shop;

void Start()
{
    shop.listofBooks.Add(new BookStore.Book());
    shop.AddNewPage(0, "hellothere");
}

But I get this error:

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

What is wrong with my code?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
ammu80q
  • 3
  • 1

1 Answers1

0

You should create an instance of your objects first. BookStore and List<Book> doesn't have instances. You have to create first like this,

BookStore shop;
void Start()
{
    shop = new BookStore();
    shop.listofBooks = new List<Book>();
    shop.listofBooks.Add(new BookStore.Book());
    shop.AddNewPage(0, "hellothere");
}

Hope helps,

Berkay Yaylacı
  • 4,383
  • 2
  • 20
  • 37