I managed to make a simple message box prefab with a Text and a Button through Canvas, and then instantiate it through the constructor.
public class MessageBox
{
public MessageBox(string msg)
{
GameObject obj = (GameObject)MonoBehaviour.Instantiate(Resources.Load(@"MsgBox"));
obj.GetComponentInChildren<Text>().text = msg;
}
}
So when another script needed it, simply do
MessageBox mb = new MessageBox("This is a test message!");
This all worked fine, but then I wish to change it to like normal MessageBox where the code was suspended, but not locked, until the user click the OK or Cancel button.
I managed to do it by calling a coroutine in the calling script.
void Start()
{
StartCoroutine("Do");
}
IEnumerator Do()
{
MessageBox mb = new MessageBox("This is also a test message!");
yield return new WaitUntil(() => GlobalVariables.MsgBoxClicked == true);
//GlobalVariables is a separate class containing some static variables.
Debug.Log("Done!");
}
(You have to set the MsgBoxClicked to false when the prefab is created and set it to true when the button is clicked, of course.)
But that means every time I needed to use the message box, I need to call a coroutine!
And that's super inefficient no matter how you looked at it!
So I tried to move the coroutine into the MessageBox class itself.
But now here comes the problem!
The MessageBox does NOT inherit from MonoBehaviour!
And you can't call a coroutine without it!
I had tried to make the MessageBox inherited from MonoBehaviour, but the Unity warned me This is not allowed every time I tried to new it! Even though the game ran smoothly.
I even tried to new the MonoBehaviour itself and call its StartCouroutine, but of course, the same warning popped up! And this time the game won't even run!
I also tried to use the old AutoResetEvent, but it locked the whole thing and crashed my game!
So, could somebody be so kind and teach me how to get around it!?
Much appreciated!