say from within a script, i call Myclass.Myfunction()
is there any way to know within myfunction, what script/object called it, without the caller having to pass itself as an argument?
say from within a script, i call Myclass.Myfunction()
is there any way to know within myfunction, what script/object called it, without the caller having to pass itself as an argument?
At the top of your class, add this import:
using System.Diagnostics;
Then in your function:
string callingFuncName = new StackFrame(1).GetMethod().Name;
You’ve answered this one yourself! You really need to pass the information from the function/script that’s doing the calling.
Is there an issue with doing that?
If it’s just too much typing consider adding methodBase to all scripts that call your function. You’ll need to add…
using System.Reflection;
then in your function
MethodBase mBase = MethodBase.GetCurrentMethod();
then call
myFunction(mBase.Name);
I suppose you could do this in monodevelop with replace in files but be careful.
Holy crap, been trying everything to get this to work, and I think I did
//Get Type of script declaring this method
System.Type type = new System.Diagnostics.StackFrame(1).GetMethod().DeclaringType;
//iterate through every instance of that type
foreach(object inst in FindObjectsOfType(type)){
//iterate through all fields(script variables) of each instance
foreach(System.Reflection.FieldInfo fi in type.GetFields()){
//if the field is of the right type
if(fi.GetValue(inst).GetType()==typeof(ThisClassType)){
//and the field value == this
if((ThisClassType)fi.GetValue(inst)==this){
Debug.Log(inst+" is the instance of the script that called this function");
}
}
}
}
Note that “ThisClassType” refers to the type of the class that this function belongs to
There is a pretty simple workaround, all you have to do is create a gameobject variable and set it to null, the add a Debug.Log(yourVariable.name) and you’ll get an error in the console detailling the history of all function calls that eventually triggered your function.