Trying to Invoke method:
BlackScreenManager.a couldn’t be
called.
So I understand invoke can’t be used with methods with parameters. But I also set a default value false if the method is being called without any parameters given. So question: How can I workaround this without creating additional methods which just call the method with the parameter?
Since you can not call Invoke with parameters you can use StartCoroutine for this.
Say your code is:
void Start()
{
Invoke("MyFunction", 1f);
}
void MyFunction()
{
// Do your thing.
}
Instead you can use Coroutine by passing argument like:
void Start()
{
StartCoroutine(MyFunction(false, 1f));
}
IEnumerator MyFunction(bool status, float delayTime)
{
yield return new WaitForSeconds(delayTime);
// Now do your thing here
}
One other option, for the sake of completeness, could be using global variables instead of method parameters. You can set those accordingly, then invoke a method that makes use of them… depending on your needs and context, this could be feasible or not, but either way it cannot hurt to be aware of the option.
public class Foo : MonoBehaviour {
private int x;
void Start () {
x = Random.Range(0, 100);
Invoke("FooBar", 5.0f);
}
private void FooBar () {
if (x == 0) {
return;
}
for (int i = 0; i < x; i++) {
Debug.Log(i);
}
}
}
HarshadK Answers will work fine . However In case you don’t want to use the Coroutine then Here it is:
Say like:
You want to call the myFoo(int a); through Invoke you can do this by taking another method invoking it and then call your function inside that method.
e.g
Start()
{
Invoke("DemoFun");
}
private void DemoFun()
{
MyFoo(int a);//Your function that you like to call
}
You can use a coroutine to WaitForSeconds, then delegates to pass arbitrary parameters to it. I use this in a static Utils class, but you could also wrap it as an extension method to insert it right into MonoBehavior.
/// <summary>
/// Like MonoBehavior.Invoke("FunctionName", 2f); but can include params. Usage:
/// Utils.RunLater( ()=> FunctionName(true, Vector.one, "or whatever parameters you want"), 2f);
/// </summary>
public static void RunLater(System.Action method, float waitSeconds) {
if (waitSeconds < 0 || method == null) {
return;
}
[SOME_MONOBEHAVIOR].StartCoroutine(RunLaterCoroutine(method, waitSeconds));
}
public static IEnumerator RunLaterCoroutine(System.Action method, float waitSeconds) {
yield return new WaitForSeconds(waitSeconds);
method();
}