- Home /
Is it possible to call a method which has optional arguments with Invoke?
void Start()
{
this.GenerateLevel(true);
}
private void GenerateLevel(bool isFirst = false)
{
if (isFirst || this.IsTimeToGenerate())
{
this.currentLevel = Instantiate(Levels[Random.Range(0, this.Levels.Length)], this.GetNewPosition(isFirst), Quaternion.identity) as GameObject;
this.currentLevel.transform.parent = this.transform;
this.previousLevel = this.currentLevel;
}
Invoke("GenerateLevel", 0.5f);
}
Is this code executable?
No, you are trying to invoke GenerateLevel(float) when you have GenerateLevel(bool). If you defined a second method GenerateLevel(float) then it would valid.
I don't try to invoke generateLevel with float. 0.5f (the second parameter I put in invoke) is for the time I want it to be executed
@deadliness Correct, at work and mixed up Invoke and StartCoroutine in my head.
Answer by SkaredCreations · Dec 19, 2014 at 02:04 AM
No, you cannot use Invoke with methods that have parameters (optional or required), but you can still use coroutine that is more elegant in your case:
void Start ()
{
StartCoroutine(GenerateLevel(true));
}
IEnumerator GenerateLevel(bool isFirst = false)
{
while (true)
{
if (isFirst || this.IsTimeToGenerate())
{
this.currentLevel = Instantiate(Levels[Random.Range(0, this.Levels.Length)], this.GetNewPosition(isFirst), Quaternion.identity) as GameObject;
this.currentLevel.transform.parent = this.transform;
this.previousLevel = this.currentLevel;
}
yield return new WaitForSeconds(0.5f);
}
}
Well, you don't really use isFirst in a meaningful way in this example since it won't change during the execution of the coroutine. This one would make more sense:
IEnumerator GenerateLevel()
{
while (true)
{
this.currentLevel = Instantiate(Levels[Random.Range(0, this.Levels.Length)], this.GetNewPosition(isFirst), Quaternion.identity) as GameObject;
this.currentLevel.transform.parent = this.transform;
this.previousLevel = this.currentLevel;
yield return null; // Just for safety in case "IsTimeToGenerate" never returns false in which case you wouldn't yield at all which would actually freeze the application.
while (!IsTimeToGenerate())
yield return new WaitForSeconds(0.5f);
}
}