Hi. I have a problem that, at the surface, seems to require a three-step init process. I know about the two-step process that Unity does provide with Awake() and Start(), but I have come to a point where I would like three steps. The following code is a simplification of the situation:
public class Manager
{
protected Action action;
public void RegisterAction (Action action)
{
this.action += action;
}
public void TriggerAction()
{
if (action != null)
{
action();
}
}
}
public class GameController : MonoBehaviour
{
public static GameController instance;
public Manager manager;
void Awake()
{
instance = this;
manager = new Manager();
}
void Start()
{
manager.TriggerEvent();
}
}
public class OtherController : MonoBehaviour
{
void OnEnable() // I want this to be called before any Start() is
// called and after ALL Awake() are called, but it
// is called immediately after the Awake() on the
// same object. (If the object is enabled, that is)
{
GameController.instance.manager.RegisterAction (OnAction);
}
protected void OnAction()
{
// Do stuff!
}
}
So, in words, I have a manager class in the model. This manager triggers actions that can be registered with it. The GameController class is a singleton-ish thing that creates the model in the Awake() method and kicks off the game in Start(), i.e. the triggers can be expected to fire in and after Start(). I have many controller objects in the scene that needs to perform actions on these triggers, they must register with the manager after it has been created but before any Start() method has been called.
Is this something that can be done? Sure, I can make every Start() in the game set a flag in the GameController and move the code in GameController.Start() to GameController.Update() surrounded by a test of that flag. However, this feels wrong.
Is there something wrong with my design pattern? Are there completely different ways of setting something like this up?
Best regards,
Fredrik
OK thank you for your help :)
– MohammedKhalid