Home > Blockchain >  Dynamically access methods from other script through string
Dynamically access methods from other script through string

Time:12-29

I have several game objects; the idea is that each time you click on any of them a pop up window with a button shows up. Depending on the object you clicked, the pop up's button performs a different function.

This is the code I'm currently using:

Script PopUpCaller- attached to each of the game objects:

public GameObject popUp;
string rewriteThis;
 
void Start()
{
    rewriteThis = gameObject.name; // Each game object's name = desired method's name. E.g. if the method's name is ActionA() then the game object's name would be ActionA.
}
 
public void TaskOnClick()
{
    popUp.SetActive(true);
    popUp.transform.position = Input.mousePosition;
    PopUp.instance.rewriteMethodName = rewriteThis;
}

Script PopUp - attached to the pop up window

public static PopUp instance;
public string rewriteMethodName;
    
private void Awake()
{
    instance = this;
}
    
void Start()
{
    gameObject.SetActive(false);
}
    
public void DoThings()
{
   GameObject.Find("MapManager").SendMessage("rewriteMethodName");   
}

Script Manager containing the methods for the game objects.

public void ActionA() //named like the corresponding game object
{
   //stuff to be done
}
    
public void ActionB() //named like the corresponding game object
{
    //other stuff to be done
}

When I run the code as it is I receive the "SendMessage rewriteMethodName has no receiver!". Now when I change "rewriteMethodName" in the PopUp script to "ActionA" or "ActionB" everything starts working, which suggests that the Manager script doesn't recognize "rewriteMethodName" even if it returns the string "ActionA" or "ActionB".

I also tried doing the same via MethodInfo and making Manager public static but it didn't work out either:

MethodInfo method =Manager.instanceManager.GetType().GetMethod("rewriteMethodName", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
method.Invoke(Manager.instanceMapManager, null);

Any suggestions how to fix it? Thank you!

CodePudding user response:

rewriteMethodName holds the method name, so should be passed in SendMessage instead of the string “rewriteMethodName”. To close out the question:

public void DoThings()
{
   GameObject.Find("MapManager").SendMessage(rewriteMethodName);   
}
  • Related