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?

EDIT: Removed comment, wrong information

> 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.

1 Answer

1

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);
		}
	}