Using Environment.StackTrace

I’m trying to debug some quite complex C# code at the moment, and I’m in a situation in which I’d like to detect where a method is being called from. I could go through my code and add print statements before every invocation, but it seems to me that it should be possible to do something a bit smarter.

After a bit of poking around in Google, I found the Environment.StackTrace feature, which looks like it’d do exactly what I want - to put the current status of the stack in a string which I can print. Unfortunately, it doesn’t seem to work. The following code:

Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);

…just prints StackTrace: ‘’

I presume this is a Mono problem rather than a Unity problem, but I’m wondering if there’s either some way of making it work, or if anyone could suggest an alternative way of getting similar information.

1 Like

from the mono page…

  public void MyMethod3 () {
        Console.WriteLine("TestCallStack: {0}",
                          Environment.StackTrace);
    }

there’s no ’ ’ around {0}. maybe?

You can use the one we use for extracting stacktraces in various situations:

string str = UnityEngine.StackTraceUtility.ExtractStackTrace ();

Depending on what you want, you might just want to call Debug.Log.

That prints the whole stacktrace to the UnityConsole too. Just select it in the console and take a look at the view in the bottom.

8 Likes

Funny, that just returns an empty string for me, too…

Thanks, that turned out to be quite sufficient for this purpose.