Hi guys, i want to build a Message Box that i can use at any point, however i found some issues.
First here is how i do it:
public class MsgBox : MonoBehaviour
{
void Update ()
{
}
public static void CreateMsgBox(string t, string b)
{
GameObject msgbox = Instantiate(Resources.Load("UI/Prefab/MessageBox")) as GameObject;
msgbox.transform.SetParent((GameObject.Find("Canvas").transform), false);
Text[] info = msgbox.GetComponentsInChildren<Text>();
info[0].text = t;
info[1].text = b;
}
}
And this is how i call it:
MsgBox.CreateMsgBox("Since this is the first time entering the Offline Netsphere, you must create a user.","Confirm");
Here is the thing though, I want to modify what happens after the “Confirm”(For example) button is clicked, And get it closed when clicked too.
So i thought adding an OnClick() on the class but that didn’t work obviously,
I guess i can solve the closing thing if add it to the prefab directly(didn’t think about it), but that’s not my main issue anyway.
How can i add an event after clicking the Button of the messagebox? I guess you could check in the Update Function if it gets destroyed, but seems kind of messy to me.
Any suggestions of how can i handle this? I would really appreciate it
One way to get a button to help in this context is to add a new public method to your script and reference this with a button that is already on the prefab.
Let’s say that you have a button on the prefab already.
You then need a public reference on your script, something like :
public void ThisButton(){
Debug.Log("This button was clicked");
}
Now you go to the inspector of the button on the prefab and at the bottom add and event with the ‘+’ symbol and select onClick().
Put the prefab containing the script into the select object.
Lastly you select the script in the function select and pick your method ThisButton() and it will print your debug (or whatever else you would like within the block).
You can ofcourse add the method to the button directly like Bioinformatizer suggested, however this couples it quite tightly with the script instead of having something you can use everywhere
Thanks for all the help guys! this is what i figured out after your two suggestions!
I made the MsgBox able to return a Button, so this way:
Button b = MsgBox.CreateMsgBox("Since this is the first time entering the Offline Netsphere, you must create a user.","Confirm");
b.onClick.AddListener(CreateName);
void CreateName()
{
Debug.Log("YOU ARE A SQUID NOOOOOOOOOOW");
}
I can add any function from anywhere i want
I got inspired by both the suggestions and the video guide, thanks you both