- Home /
Checking if a method with a certain name exists through code! v
Hi,
In my Code i am Invoking methods with strings that contain Spellnames:
string Spellname = "FireBall";
Invoke(Spellname, 0);
This obviously thorws an error when there is no funktion named "FireBall". So my question is:
Can i check if a funktion with a specific name extists?
Something like:
If (*funktion named FireBall exists*){
Invoke (Spellname,0);}
else{
*alternative Route*
}
Thank you Guys!
Comment
Best Answer
Answer by nutraj · Aug 03, 2020 at 12:20 PM
Sure, you can use System.Type
in C# to do exactly that.
Here's the method code:
public bool CheckMethod(string funcName)
{
var thisType = this.GetType();
if (thisType.GetMethod(funcName) != null)
{
return true;
}
else
{
Debug.LogErrorFormat("Method of Name {0} doesn't exist!", funcName);
return false;
}
}
So the way to use it in your code will be :
if(CheckMethod("FireBall"))
{
Invoke("FireBall", 1f);
}
else
{
// Something else
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613004804im_/https://answers.unity.com/themes/thub/images/avi.jpg)