- Home /
How can I get the name of a coroutine method using a StackTrace?
Stack traces currently only show coroutine functions as "MoveNext" which is not what i want. Here's my test code:
using UnityEngine;
using System.Collections;
using System.Diagnostics;
public class TestCoroutineStackTrace : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
TestStackTrace();
yield return null;
}
void TestStackTrace() {
StackTrace theTrace = new StackTrace();
foreach(StackFrame f in theTrace.GetFrames()) {
UnityEngine.Debug.Log(f.GetMethod().Name);
}
}
}
Output:
TestStackTrace
UnityEngine.Debug:Log(Object)
MoveNext
UnityEngine.Debug:Log(Object)
Answer by kromenak · Mar 15, 2013 at 05:48 AM
I'm not at all familiar with System.Diagnostics (so it may contain a way to do this), but you might be able to use Unity's built-in StackTraceUtility class. Since Unity's stack traces always put coroutines inside of characters, you can get the current coroutine using something like this:
private IEnumerator TestCoroutine()
{
string stackTrace = StackTraceUtility.ExtractStackTrace();
string coroutineName = stackTrace.Substring(stackTrace.IndexOf('<') + 1, stackTrace.IndexOf('>') - 1);
Debug.Log(coroutineName);
yield break;
}
I don't know what your ultimate goal is (and maybe you really need to use StackFrame for some reason), but this should get you the coroutine name.
Unity's StackTraceUtility returns this:
Game$$anonymous$$anger:GameUpdateDebug() (at Assets/Tone Assets/Scripts/Singletons/Game$$anonymous$$anger.cs:342) c__IteratorF:$$anonymous$$oveNext() (at Assets/Tone Assets/Scripts/Singletons/Game$$anonymous$$anger.cs:292)
It's "GameUpdate" (stackframe(1)) that I'm looking for specifically and it's in there but only as part of the full name which I'd have to fish out. The same data exists for the regular .net version too.
$$anonymous$$y purpose is just to be careful about running debug code so that it can only be called from one particular function. Not really necessary but it helps me be explicit about my code's intentions.
Answer by insominx · Mar 15, 2013 at 04:37 PM
Here's how to do it using .net's System.Diagnostics:
System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace();
string fullName = st.GetFrame(1).GetMethod().ReflectedType.Name;
string coroutineMethodName = fullName.Substring(fullName.IndexOf('<') + 1, fullName.IndexOf('>') - 1);
I'm not sure the pros or cons of using either. Maybe only Unity version is available to javascript and boo?
Your answer
Follow this Question
Related Questions
Weird coroutine behaviour, speed increases too much 2 Answers
Why isn't this coroutine fully firing? 1 Answer
Get a stack trace to find unknown caller 0 Answers
How to debug a coroutine? 2 Answers