I'm working on a game project in Unity with a point and click interface and I'm trying to make a method that moves the player towards a target object and invokes another method depending on what the target object is.
I'm running into two problems: first, when I try to pass the method as a parameter, it immediately runs it. For example, the following code is given to the Unity UI to create a button that is supposed to make the player move towards a target and then open a pop up menu. AB_PathAct is the method that moves the player, the first parameter is the player's destination, and the second parameter is a method, CoMuOpen, which AB_PathAct is supposed to use when the player reaches the destination. CoMuOpen has it's own parameters. Instead, when the following code runs, both parts happen at once: The player is sent towards the target, and the menu immediately opens. In other words, the code isn't even trying to pass the CoMuOpen call as a parameter of AB_PathAct, it's just calling it.
public void ButtonCMDInvokeTarget()
{
AB_PathAct(
r_hit.collider.gameObject,
CoMuOpen(
popMenus[1],
Camera.main.WorldToScreenPoint(
r_hit.collider.gameObject.transform.position
)
),
tarDist
);
}
The second problem is that AB_PathAct isn't actually taking that method as a parameter; when AB_PathAct reaches its destination, it fails to invoke the method that is its second parameter. I know why this is happening; CoMuOpen returns a string and AB_PathAct takes a string as it's second parameter. What I want to do is replace AB_PathAct's string parameter with a method.
To put it simply, I need to replace two lines of AB_PathAct to make it do what I actually want, but I don't know what to replace them with. Everything in the following code functions correctly except the problem code, which is surrounded by asterisks below (the actual code doesn't have them, obviously).
void AB_PathAct(GameObject comTar, **string methodToInvoke**, float tarDist)
{
if (Vector3.Distance(transform.position, comTar.transform.position) > tarDist)
{
agent.destination = comTar.transform.position;
mr_moveGoal.enabled = true;
moveGoal.transform.position = new Vector3(comTar.transform.position.x, moveGoal.transform.position.y, comTar.transform.position.z);
}
else if (Vector3.Distance(transform.position, comTar.transform.position) <= tarDist)
{
agent.ResetPath();
**StartCoroutine(methodToInvoke);**
}
}
Is it possible to make a method take another method call as a parameter?
EDIT: Here's the CoMuOpen code for reference. It's a very simple function that works as intended when invoked directly or through UnityUI. Returning a string isn't important and I'll probably remove it.
public string CoMuOpen(GameObject tarMen, Vector3 tarPos)
{
tarMen.transform.position = tarPos;
tarMen.SetActive(true);
return "Open Context Menu";
}