问题
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 theAdd
method is likely to correspond toqueue
.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:
Go to the Debug menu.
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