I do not believe that this is possible. Considering the source code for Environment.StackTrace and the subsequent GetStackTrace() call, we can see it creates a stack trace every time it is called. Since there is nothing that could be done to change part of its work, I think it is safe to conclude that you cannot change the stacktrace without changing what it is called.
If you have the opportunity to do this, you can use something like this, which boils down to fetching the current stacktrace and using reflection to modify the very latest StackFrame method to mimic what you need.
void Main() { DoSomething(); } void DoSomething(){ Console.WriteLine (Environment.StackTrace); // Last frame: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) var frames = new StackTrace().GetFrames(); var lastframe = frames[0]; // last frame: DoSomething at offset 100 in file:line:column <filename unknown>:0:0 var methodField = lastframe.GetType().GetField("method", BindingFlags.Instance | BindingFlags.NonPublic); var redirectedMethod = typeof(Redirect).GetMethod("RedirectToMethod", BindingFlags.Instance | BindingFlags.Public); methodField.SetValue(lastframe, redirectedMethod); Console.WriteLine (frames); // last frame: RedirectToMethod at offset 100 in file:line:column <filename unknown>:0:0 Console.WriteLine (Environment.StackTrace); // last frame: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) } public class Redirect { public void RedirectToMethod() { } }
But again: this is very fragile and not applicable in your current situation. What you are trying to do is quite exotic and should probably be avoided altogether.
As for the real solution: I'm afraid that I have no experience with Unity, so I can only google, but this stream might be interesting for you. I mentioned .NET sources here, but you can find very similar code in the Mono source.
Jeroen vannevel
source share