StreamWriter only exists between curly braces

In the development of the game I’m working on, it has become necessary to have a separate debug file for each unit (this is an RTS game). After a bit of time on Google, I came across the StreamWriter class. It looked pretty awesome, so I added a StreamWriter (named writer) to my code, instantiated it in Awake(), and put some writer.WriteLine() statements in my update function. Everything was beautiful, until I hit the pay button. I found quite quickly that I was getting a NullReferenceException every time I called writer.WriteLine(). This was odd. Hadn’t I just instantiated writer in Awake()? So I threw some writer.WriteLine()'s in Awake, and viola! it worked.

I then decided to see if initializing writer when I declare it might be a better idea. I tried that and all the NullReferenceExceptions were gone! However, no data was actually written to any file.

Here’s the declaration I used when writer was instantiated outside of a function:

StreamWriter writer = new StreamWriter("C:/Users/DAVID/AppData/LocalLow/Jotun Studios/Warfare 2525/Unit" + id + ".udb");

(note that id is a static long property which increases by 1 every time it’s accessed)

Here’s the instantiation I used in Awake():

StreamWriter writer;
void Awake()
{
    writer = new StreamWriterApplication.persistentDataPath +"/Unit" + id + ".udb");
}

From the above tests, I have come to the conclusion that I’d have to re-instantiate writer in Update(), which would have way too much of a performance impact. I don’t know everything, though, so I was hoping one of you lovely forum users could help.

Do any of you have any idea how I can write data to a file of my choosing every frame?

You’re creating a new local variable in Awake? Variables must be declared globally (outside functions) if you want to use them in more than one function.

–Eric

No, that’s a typo. writer was always declared outside of a function. Lemme edit the first post.