Coroutine Chain of Events

I have functionality in my game where an action has several steps in order to be completed.

I want it to perform this sequence:

  1. Click button X to start the chain of
    events. (Start coroutine #1)
  2. Click button to complete Step 1.
  3. Click button to complete
    Step 2.
  4. Click button to complete the process.

Here is a sketch I drew up to try to convey what I mean:
alt text

‘Do Something’ is the normal operation of the object, and should be skipped completely when in the middle of this multi-step process.

I tried nesting co-routines but clearly did something wrong, what happens now is that all of the steps complete on the first click.

Thanks

Hey Avidesk:

I used this Chaining actions over time and in order - Questions & Answers - Unity Discussions to came up with a chained event manager script. Basically its a monobehavior that has a list of routine names.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class ChainedEventsManager : MonoBehaviour {

	public int EventId;	
	public List<string> ChainedEvents;
	public bool IsExecuting = false;
//	
	public void NextTask(int nextId)
	{
	   EventId = nextId;
	   //audio.Play();
	}

	void Update()
	{
	   	if(EventId >= 0 && !IsExecuting)
		{ 
			IsExecuting = true;
			//Execute Next chained action	      
	      	SendMessageUpwards(ChainedEvents[EventId]);	 
			//if is the last item on the chain, set the event id to -1 so the cycle is not hit anymore
			if (EventId == ChainedEvents.Count)
			{
				EventId = -1;
			}
	      
	   	}
	}
}

Then I used the ChainedEvents list to set up the names of the functions that I want to execute on the correct order. So lets say the order if chained events list is [“FunctionA”, “FunctionB”] I have something like this:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;


public class ChainedEventsPuzzle: MonoBehaviour {
  private ChainedEventsManager eventManager;
  
  void Start()
  {
     eventManager = transform.GetComponent<ChainedEventsManager>();
  }
}

  void StartChainedEvents()
  {
      //Set the id to 0, so the chain starts
      eventManager.NextTask(0);
  }

  void FunctionA()
  {
     //Do Function A
     eventManager.NextTask(1);
     eventManager.IsExecuting = false;
  }

   //Async function
  void FunctionB()
  {
     //Do function B

     //Call execution Async
     StartCoroutine(DoSomethingAsync();
  }

  IEnumerator DoSomethingAsync()
  {
     //Do Something

     yield return new WaitForSeconds(SecondsToWait); //I use this to wait an animation to end
     //Break the chained events	
    eventManager.NextTask(-1);
    eventManager.IsExecuting = false;
     
  }

}

At anytime you could break the event chain by executing eventManager.Nextask(-1). I guess you could set your own flags for the buttons to know when the chainmanager should continue with the next chained even.

Hope it helps.