Your question reminded me of something in my programming class - type polymorphism!
And I was curious whether this can be used in Unity. So I took the time to put it together.
The idea is to have a basic quest class:
using UnityEngine;
using System.Collections;
// BaseQuest derives from MonoBehaviour, so it can be added to GameObjects
// abstract means: this class does not implement any functions, it only says which functions
// must be implemented in derived classes
public abstract class BaseQuest : MonoBehaviour
{
// here we have the basic quest behaviour - each derived class knows what to do with this function
public abstract string QuestText();
}
This script is never actually added to any GameObject, its just the base for other quest scripts:
A simple quest:
using UnityEngine;
using System.Collections;
// a simple quest is a quest - so it derives from the BaseQuest class
public class SimpleQuest : BaseQuest
{
void Start () {}
// the "old" QuestText method from BaseQuest gets overwritten
public override string QuestText()
{
return ("I am a simple quest!");
}
}
A more advanced quest:
using UnityEngine;
using System.Collections;
// an advanced quest is a quest - so it derives from the BaseQuest class
public class AdvancedQuest : BaseQuest
{
void Start () {}
// the "old" QuestText method from BaseQuest gets overwritten
public override string QuestText()
{
return ("I am an advanced quest!");
}
}
Right now, you can add the AdvancedQuest and SimpleQuest scripts to a GameObject as many times as you want.
Now comes the script that handles everything:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class QuestHandler : MonoBehaviour {
// This list handles all the quests
private List<BaseQuest> quests;
void Start ()
{
// the quests list gets created
quests = new List<BaseQuest>();
// collecting all the quests from the GameObject (the player)
Component[] questsComps = gameObject.GetComponents(typeof(BaseQuest));
foreach(Component comp in questsComps)
{
// adding the quest to the list
addQuest(comp as BaseQuest);
}
// each quest shows his message
foreach (BaseQuest quest in quests)
// here comes the magic - type polymorphism!
// all quests in the list derive from BaseQuest, which has this function
// all the derived quests override the QuestText function with their own behaviour
Debug.Log(quest.QuestText());
}
void addQuest(BaseQuest q)
{
// adding the quest to the list
quests.Add(q);
}
}
It gets added to the same GameObject. On Start(), it collects all the scripts of BaseQuest class and all its derivates (this was were I wasn't sure Unity would handle it in this (right) way). All the quests get added to a quests List of BaseQuest objects.
And then every quest is asked to return its QuestText - and due to the type polymorphism, the right QuestText method is chosen and executed.
Thanks for this cool question!