Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An inheritance-based messaging system for executing behaviour based on enumerations.
//Add whatever keywords are relevant to your project here.
public enum Cue
{
None,
Spawn,
Destroy,
Stop,
Pause,
Start,
Refresh
}
public class CueBehaviour : MonoBehaviour {
public bool executeOnStart;
public int onStartIndex;
public Cue[] cues;
private void Start()
{
if (executeOnStart)
{
ExecuteBehaviour(onStartIndex);
}
}
public virtual void ExecuteBehaviour(int index)
{
//Subclasses can override this with the desired behaviour.
}
}
public class CueProcessor : MonoBehaviour {
public Cue loadBehavioursCue = Cue.Refresh;
protected CueBehaviour[] behaviours;
public void Awake()
{
LoadBehaviours();
}
public virtual void ProcessCue(Cue cue)
{
if (cue != Cue.None)
{
if(cue == loadBehavioursCue)
{
LoadBehaviours();
}
for (int i = 0; i < behaviours.Length; i++)
{
if (behaviours[i] != null)
{
for (int c = 0; c < behaviours[i].cues.Length; c++)
{
if (behaviours[i].cues[c] == cue)
{
behaviours[i].ExecuteBehaviour(c);
}
}
}
}
}
}
public void LoadBehaviours()
{
behaviours = GetComponentsInChildren<CueBehaviour>();
}
}
//An example of how a simple CueBehaviour would look like.
public class EmissionOnCue : CueBehaviour {
public ParticleSystem targetParticles;
public bool[] emit;
private ParticleSystem.EmissionModule module;
void Start()
{
module = targetParticles.emission;
}
//This method is called only if there's a match in cues, called by the CueProcessor.
public override void ExecuteBehaviour(int index)
{
module.enabled = emit[index];
}
}
//Another example of a CueBehaviour that both sends and receives Cues.
public class SendCueOnCue : CueBehaviour {
public CueProcessor[] targetProcessor;
public Cue[] cueToSend;
public float[] delayInSeconds;
public override void ExecuteBehaviour(int index)
{
StartCoroutine(FireCue(index));
}
public IEnumerator FireCue(int index)
{
yield return new WaitForSeconds(delayInSeconds[index]);
if (targetProcessor[index] != null)
{
targetProcessor[index].ProcessCue(cueToSend[index]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment