C# Object Reference not set to an instance of an object error [duplicate]

谁都会走 提交于 2020-01-16 01:11:13

问题


I am getting the error in the title when I run this code during the Add method. The Add method should add the gameobject to a list called queue.
GameObject is a class.
GameManager is a class as well.
queue is a list.

I think this is the only code relevant.

    static void Main()
    {
        GameObject obj1 = new GameObject();
        GameManager manager1 = new GameManager();
        obj1.name = "First";
        manager1.Add(obj1);
        manager1.Process();
    }

    public void Add(GameObject gameObject)
    {
        gameObject.initialize = true;
        queue.Add(gameObject);
    }

回答1:


Try initializing the field "queue":

  • It's probably never initialized, hence the Object Reference not set to an instance of an object error error, which by the structure of the Add method is likely to correspond to queue.

  • Also - I would consider renaming queue to a meaningful name, since it is currently deceiving.

Here is an initialization suggestion, it is for a List as you described in your question, but can easily be modified to correspond to any IEnumerable , also, it can be done in a different method being executed prior to Main (again, by the looks of your code it seems unlikely) :

private List<GameObject> queue; // assuming it's private, doesn't really matter either way.

static void Main()
{
    queue = new List<GameObject>(); // the missing line
    GameObject obj1 = new GameObject();
    GameManager manager1 = new GameManager();
    obj1.name = "First";
    manager1.Add(obj1);
    manager1.Process();
}


public void Add(GameObject gameObject)
{
    gameObject.initialize = true;
    queue.Add(gameObject);
}



回答2:


You have to initialize Queue list first




回答3:


You need to debug your code.

I assume you are using Visual Studio, if so then do this:

  1. Go to the Debug menu.

  2. Click on the the Exceptions... choice.

The following dialog should appear:

Note: the Common Language Runtime Exceptions checkbox is checked.

Upon clicking OK, now when you debug your code anytime an exception is thrown by your code or the .NET Framework, the debugger will halt on the line that threw the exception. This makes finding where something is "breaking" much easier.



来源:https://stackoverflow.com/questions/17557083/c-sharp-object-reference-not-set-to-an-instance-of-an-object-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!