In my project I'm implementing an action class and was wondering if it was possible to pass a function as a parameter like this:
public class Action : MonoBehavior {
public int ID;
public string Name;
//Test variable to store a function here
}
Where later I would create a function, such as this one, and call it.
void TestFunction() {
print("Test");
}
public Action ExampleAction;
ExampleAction.Test = TestFunction();
And then finally I could simply call "Action.Test" to run TestFunction.
I've done some research on the topic and I believe it's somewhat related to delegation but how could I do it in this scenario?
And even more, is this sort of implementation reliable or the nicest way to do it? In my project I plan on having a lot of toggleable actions, that when clicked, will continuously do a large variety of different things.
CodePudding user response:
The name Action
is actually already used to represent a specific type of delegate, so I would recommend renaming your Action class to something more specific and then leverage the built-in Action
type for your Test property.
public class ActionMonoBehavior : MonoBehavior {
public int ID;
public string Name;
public Action Test;
}
public ActionMonoBehavior ExampleAction = new ActionMonoBehavior
{
ID = 1,
Name = "Example"
Test = TestFunction // or () => TestFunction()
};
ExampleAction.Test(); // or ExampleAction.Test.Invoke();
CodePudding user response:
To my understanding, what you are trying to do is create a parameterized delegate.
I think UnityAction
fit this perfectly.
UnityAction
is a built-in delegate that takes no parameters and returns no value.
In your case, you would want to use a parameterized UnityAction<T1, T2>
, where you would set T1
to int and T2
to string.
Here is a snippet for demonstration:
using UnityEngine;
using UnityEngine.Events;
public class UnityActionDemo
{
UnityAction<int, string> action;
private void Start()
{
action = TestMethod;
}
public void TestMethod(int id, string name)
{
Debug.Log("id is: " id "\t name is: " name);
}
}
action
can then be passed around to any method that takes a UnityAction<int, string>
as a parameter.
In order to invoke the method, call action.Invoke
with the parameters you'd like to use:
action.Invoke(27, "A cool method name");
:)